프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 77a869a8

이력 | 보기 | 이력해설 | 다운로드 (290 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
                        // Target Item에 Label의 Attribute Input
1905
                        InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1906

    
1907
                        // LEADER Line 검사
1908
                        bool leaderLine = false;
1909
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1910
                        if (symbolMapping != null)
1911
                            leaderLine = symbolMapping.LEADERLINE;
1912

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

    
1923
                    foreach (var item in connectorVertices)
1924
                        if (item.Key != null)
1925
                            ReleaseCOMObjects(item.Key);
1926
                }
1927
            }
1928
        }
1929

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

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

    
1947
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1948

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

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

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

    
2001
            if (targetItem != null)
2002
            {
2003
                ReleaseCOMObjects(targetItem);
2004
            }
2005

    
2006
            ReleaseCOMObjects(_LMSymbol);
2007
        }
2008

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

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

    
2025
                ReleaseCOMObjects(symbol);
2026
                symbol = null;
2027
            }
2028
        }
2029

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

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

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

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

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

    
2124
                                    // Range 겹치는지 확인해야함
2125
                                    double[] prevRange = null;
2126
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2127
                                    double[] groupRange = null;
2128
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2129

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

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

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

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

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

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

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

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

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

    
2278

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

    
2287
            List<Line> group = new List<Line>();
2288
            GetConnectedLineGroup(line, group);
2289
            LineCoordinateCorrection(group);
2290

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

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

    
2372
                            placeRunInputs.AddPoint(x, y);
2373

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

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

    
2400
                    bool bRemodelingStart = false;
2401
                    if (_LMSymbolStart != null)
2402
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2403
                    bool bRemodelingEnd = false;
2404
                    if (_LMSymbolEnd != null)
2405
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2406

    
2407
                    if (bRemodelingStart || bRemodelingEnd)
2408
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2409

    
2410
                    FlowMarkModeling(groupLine);
2411

    
2412
                    ReleaseCOMObjects(_lMConnector);
2413

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

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

    
2437
                foreach (var item in removeLines)
2438
                    RemoveLineForModeling(item as Line);
2439

    
2440
                ReleaseCOMObjects(_LMAItem);
2441
                _LMAItem = null;
2442
                ReleaseCOMObjects(placeRunInputs);
2443
                placeRunInputs = null;
2444
                ReleaseCOMObjects(_LMSymbolStart);
2445
                _LMSymbolStart = null;
2446
                ReleaseCOMObjects(_LMSymbolEnd);
2447
                _LMSymbolEnd = null;
2448

    
2449
                if (isBranchModeling && BranchLines.Contains(groupLine))
2450
                    BranchLines.Remove(groupLine);
2451
            }
2452
        }
2453

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

    
2515
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2516
            if (_lMConnector != null)
2517
                _lMConnector.Commit();
2518

    
2519
            ReleaseCOMObjects(_LMAItem);
2520
            _LMAItem = null;
2521
            ReleaseCOMObjects(placeRunInputs);
2522
            placeRunInputs = null;
2523
            ReleaseCOMObjects(_LMSymbolStart);
2524
            _LMSymbolStart = null;
2525
            ReleaseCOMObjects(_LMSymbolEnd);
2526
            _LMSymbolEnd = null;
2527

    
2528
            return _lMConnector;
2529
        }
2530

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

    
2559
                ReleaseCOMObjects(modelItem);
2560
            }
2561
        }
2562

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

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

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

    
2607
            // 역으로 심볼이 있을 경우 좌표 보정
2608
            LineCoordinateCorrectionForLastLine(group);
2609
        }
2610

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

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

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

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

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

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

    
2695
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2696
        }
2697

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

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

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

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

    
2766
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2767
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2768
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2769

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

    
2774
                if (startSpecBreak != null || startEndBreak != null)
2775
                    result = true;
2776
            }
2777
        }
2778

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

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

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

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

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

    
2867
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2868
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2869

    
2870
            ReleaseCOMObjects(placeRunInputs);
2871
            ReleaseCOMObjects(_LMAItem);
2872
            ReleaseCOMObjects(modelItem);
2873

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

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

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

    
2919
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2920
                ReleaseCOMObjects(newConnector);
2921
            }
2922

    
2923
            ReleaseCOMObjects(modelItem);
2924
        }
2925

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

    
2948
                    if (result)
2949
                        break;
2950
                }
2951
            }
2952
            foreach (var item in dicVertices)
2953
                ReleaseCOMObjects(item.Key);
2954
        }
2955

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

    
2981
                            if (child != null)
2982
                                break;
2983
                        }
2984

    
2985
                        if (child != null)
2986
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2987
                    }
2988

    
2989
                    break;
2990
                }
2991
            }
2992

    
2993
            return _LMSymbol;
2994
        }
2995

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

    
3012
            return null;
3013
        }
3014

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

    
3024
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3025
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3026
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3027

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

    
3036
                SegmentLocation location;
3037
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3038
                Array array = null;
3039
                if (point != null)
3040
                    array = new double[] { 0, point[0], point[1] };
3041
                else
3042
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3043
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3044
                if (_LmLabelPersist != null)
3045
                {
3046
                    _LmLabelPersist.Commit();
3047
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3048
                    if (_LmLabelPersist.ModelItemObject != null)
3049
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3050
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3051

    
3052
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3053

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

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

    
3073
            if (location.HasFlag(SegmentLocation.Right))
3074
                x = GridSetting.GetInstance().Length * 3;
3075
            else if (location.HasFlag(SegmentLocation.Left))
3076
                x = -GridSetting.GetInstance().Length * 3;
3077

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

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

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

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

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

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

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

    
3168
            return newConnector;
3169
        }
3170

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

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

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

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

    
3214
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3215

    
3216
                                ReleaseCOMObjects(_LmLabelPersist);
3217
                            }
3218

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

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

    
3245
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3246
                {
3247
                    if (connector.get_ItemStatus() != "Active")
3248
                        continue;
3249

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

    
3262
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3263
                {
3264
                    if (connector.get_ItemStatus() != "Active")
3265
                        continue;
3266

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

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

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

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

    
3298
                            if (IsConnected(_LMConnector, connectedModelItem))
3299
                                targetConnector = _LMConnector;
3300
                            else
3301
                                ReleaseCOMObjects(_LMConnector);
3302
                        }
3303
                    }
3304

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

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

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

    
3335
                        if (IsConnected(connector, targetModelItem))
3336
                        {
3337
                            targetConnector = connector;
3338
                            break;
3339
                        }
3340
                    }
3341

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

    
3349
                            if (IsConnected(connector, targetModelItem))
3350
                            {
3351
                                targetConnector = connector;
3352
                                break;
3353
                            }
3354
                        }
3355
                    }
3356
                }
3357

    
3358
            }
3359

    
3360
            return targetConnector;
3361
        }
3362

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

    
3410
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3411

    
3412
                    ReleaseCOMObjects(modelItem);
3413
                    ReleaseCOMObjects(connectedConnector);
3414

    
3415
                    if (vertices.Count > 0)
3416
                    {
3417
                        if (connIndex == 1)
3418
                            result = vertices[0];
3419
                        else if (connIndex == 2)
3420
                            result = vertices[vertices.Count - 1];
3421

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

    
3457
            return result;
3458
        }
3459

    
3460
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3461
        {
3462
            bool result = false;
3463

    
3464
            foreach (LMRepresentation rep in modelItem.Representations)
3465
            {
3466
                if (result)
3467
                    break;
3468

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

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

    
3506
                    ReleaseCOMObjects(_LMConnector);
3507
                }
3508
            }
3509

    
3510

    
3511
            return result;
3512
        }
3513

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

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

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

    
3558
                    if (connectedConnector == null)
3559
                        ReleaseCOMObjects(_LMConnector);
3560
                }
3561
            }
3562
        }
3563

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

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

    
3599
                // item2가 item1으로 조인
3600
                _placement.PIDJoinRuns(ref item1, ref item2);
3601
                item1.Commit();
3602
                item2.Commit();
3603

    
3604
                string beforeID = string.Empty;
3605
                string afterID = string.Empty;
3606

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

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

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

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

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

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

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

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

    
3701

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

    
3710
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3711
            {
3712
                if (connector.get_ItemStatus() != "Active")
3713
                    continue;
3714

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

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

    
3726
                if (temp.Contains(modelItem.Id))
3727
                    connectors.Add(connector);
3728
                ReleaseCOMObjects(connOtherSymbol);
3729
                connOtherSymbol = null;
3730
                ReleaseCOMObjects(modelItem);
3731
                modelItem = null;
3732
            }
3733

    
3734

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

    
3756
            foreach (var connector in connectors)
3757
                ReleaseCOMObjects(connector);
3758
            
3759
            return result;
3760

    
3761

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

    
3770
                return findResult;
3771
            }
3772
        }
3773

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

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

    
3814
                ReleaseCOMObjects(modelItem);
3815
            }
3816

    
3817
            return connectorVertices;
3818
        }
3819

    
3820
        private List<double[]> GetConnectorVertices(LMConnector connector)
3821
        {
3822
            List<double[]> vertices = new List<double[]>();
3823
            if (connector != null)
3824
            {
3825
                dynamic OID = connector.get_GraphicOID().ToString();
3826
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3827
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3828
                int verticesCount = lineStringGeometry.VertexCount;
3829
                double[] value = null;
3830
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3831
                for (int i = 0; i < verticesCount; i++)
3832
                {
3833
                    double x = 0;
3834
                    double y = 0;
3835
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3836
                    vertices.Add(new double[] { x, y });
3837
                }
3838
            }
3839
            return vertices;
3840
        }
3841

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

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

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

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

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

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

    
3970
            return targetConnector;
3971
        }
3972

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

    
3979
            double length = double.MaxValue;
3980
            LMConnector targetConnector = null;
3981
            double[] resultPoint = null;
3982
            List<double[]> targetVertices = null;
3983

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

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

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

    
4014
                    double maxLineX = Math.Max(point1[0], point2[0]);
4015
                    double minLineX = Math.Min(point1[0], point2[0]);
4016
                    double maxLineY = Math.Max(point1[1], point2[1]);
4017
                    double minLineY = Math.Min(point1[1], point2[1]);
4018

    
4019
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4020

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

    
4057
            foreach (var item in vertices)
4058
                if (item.Key != null && item.Key != targetConnector)
4059
                    ReleaseCOMObjects(item.Key);
4060

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

    
4067
                GridSetting gridSetting = GridSetting.GetInstance();
4068

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

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

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

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

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

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

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

    
4228
            x = resultPoint[0];
4229
            y = resultPoint[1];
4230

    
4231
            return targetConnector;
4232
        }
4233

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

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

    
4248
                ReleaseCOMObjects(modelItem);
4249
            }
4250

    
4251
            if (connectors.Count == 1)
4252
                result = connectors[0];
4253
            else
4254
                foreach (var item in connectors)
4255
                    ReleaseCOMObjects(item);
4256

    
4257
            return result;
4258
        }
4259

    
4260
        private LMConnector GetLMConnectorFirst(string modelItemID)
4261
        {
4262
            LMConnector result = null;
4263
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4264

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

    
4289
            return result;
4290
        }
4291

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

    
4307
            return result;
4308
        }
4309

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

    
4324
            return result;
4325
        }
4326

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

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

    
4345
                    if (_LmLabelPresist != null)
4346
                    {
4347
                        _LmLabelPresist.Commit();
4348
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4349
                        ReleaseCOMObjects(_LmLabelPresist);
4350
                    }
4351
                }
4352

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

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

    
4371
                    GridSetting gridSetting = GridSetting.GetInstance();
4372
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4373

    
4374
                    double[] labelRange = null;
4375
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4376
                    List<double[]> vertices = GetConnectorVertices(connector);
4377

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

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

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

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

    
4426
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4427
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4428
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4429
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4430

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

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

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

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

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

    
4509
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4510
                        {
4511
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4512
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4513
                        }
4514
                    }
4515

    
4516

    
4517
                    ReleaseCOMObjects(connector);
4518
                    connector = null;
4519
                }
4520

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

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

    
4566
                return 0;
4567
            }
4568

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

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

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

    
4666
        /// <summary>
4667
        /// Symbol Attribute 입력 메서드
4668
        /// </summary>
4669
        /// <param name="item"></param>
4670
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4671
        {
4672
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4673
            string sRep = null;
4674
            string sModelID = null;
4675
            if (targetItem.GetType() == typeof(Symbol))
4676
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4677
            else if (targetItem.GetType() == typeof(Equipment))
4678
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4679
            else if (targetItem.GetType() == typeof(Line))
4680
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
4681
            
4682
            if (!string.IsNullOrEmpty(sRep))
4683
            {
4684
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4685
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4686
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4687
                
4688
                foreach (var item in targetAttributes)
4689
                {
4690
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4691
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4692
                    {
4693
                        if (!mapping.IsText)
4694
                        {
4695
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4696
                            if (_Attribute != null)
4697
                            {
4698
                                _Attribute.set_Value(item.VALUE);
4699
                                // OPC 일경우 Attribute 저장
4700
                                if (targetItem.GetType() == typeof(Symbol))
4701
                                {
4702
                                    Symbol symbol = targetItem as Symbol;
4703
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4704
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4705
                                }
4706
                            }
4707
                        }
4708
                        else
4709
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
4710
                    }
4711
                }
4712
                _LMModelItem.Commit();
4713

    
4714
                ReleaseCOMObjects(_Attributes);
4715
                ReleaseCOMObjects(_LMModelItem);
4716
                ReleaseCOMObjects(_LMSymbol);
4717
            }
4718
            else if (!string.IsNullOrEmpty(sModelID))
4719
            {
4720
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
4721
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4722

    
4723
                foreach (var item in targetAttributes)
4724
                {
4725
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4726
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4727
                    {
4728
                        if (!mapping.IsText)
4729
                        {
4730
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4731
                            if (_Attribute != null)
4732
                                _Attribute.set_Value(item.VALUE);
4733
                        }
4734
                    }
4735
                }
4736
                _LMModelItem.Commit();
4737

    
4738
                ReleaseCOMObjects(_Attributes);
4739
                ReleaseCOMObjects(_LMModelItem);
4740
            }
4741
        }
4742

    
4743
        /// <summary>
4744
        /// Input SpecBreak Attribute
4745
        /// </summary>
4746
        /// <param name="specBreak"></param>
4747
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4748
        {
4749
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4750
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4751

    
4752
            if (upStreamObj != null &&
4753
                downStreamObj != null)
4754
            {
4755
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4756

    
4757
                if (targetLMConnector != null)
4758
                {
4759
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4760
                    {
4761
                        string symbolPath = _LMLabelPersist.get_FileName();
4762
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4763
                        if (mapping != null)
4764
                        {
4765
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4766
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4767
                            {
4768
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4769
                                if (values.Length == 2)
4770
                                {
4771
                                    string upStreamValue = values[0];
4772
                                    string downStreamValue = values[1];
4773

    
4774
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4775
                                }
4776
                            }
4777
                        }
4778
                    }
4779

    
4780
                    ReleaseCOMObjects(targetLMConnector);
4781
                }
4782
            }
4783

    
4784

    
4785
            #region 내부에서만 쓰는 메서드
4786
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4787
            {
4788
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4789
                Line upStreamLine = _upStreamObj as Line;
4790
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4791
                Line downStreamLine = _downStreamObj as Line;
4792
                // 둘다 Line일 경우
4793
                if (upStreamLine != null && downStreamLine != null)
4794
                {
4795
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4796
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4797
                }
4798
                // 둘다 Symbol일 경우
4799
                else if (upStreamSymbol != null && downStreamSymbol != null)
4800
                {
4801
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4802
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4803
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4804

    
4805
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4806
                    {
4807
                        if (connector.get_ItemStatus() != "Active")
4808
                            continue;
4809

    
4810
                        if (connector.Id != zeroLenthConnector.Id)
4811
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4812
                    }
4813

    
4814
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4815
                    {
4816
                        if (connector.get_ItemStatus() != "Active")
4817
                            continue;
4818

    
4819
                        if (connector.Id != zeroLenthConnector.Id)
4820
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4821
                    }
4822

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

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

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

    
4837
                        if (connector.Id != zeroLenthConnector.Id)
4838
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4839
                    }
4840

    
4841
                    ReleaseCOMObjects(zeroLenthConnector);
4842
                    ReleaseCOMObjects(upStreamLMSymbol);
4843
                    ReleaseCOMObjects(downStreamLMSymbol);
4844
                }
4845
                else if (upStreamSymbol != null && downStreamLine != null)
4846
                {
4847
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4848
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4849
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4850

    
4851
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4852
                    {
4853
                        if (connector.get_ItemStatus() != "Active")
4854
                            continue;
4855

    
4856
                        if (connector.Id == zeroLenthConnector.Id)
4857
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4858
                    }
4859

    
4860
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4861
                    {
4862
                        if (connector.get_ItemStatus() != "Active")
4863
                            continue;
4864

    
4865
                        if (connector.Id == zeroLenthConnector.Id)
4866
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4867
                    }
4868

    
4869
                    ReleaseCOMObjects(zeroLenthConnector);
4870
                    ReleaseCOMObjects(upStreamLMSymbol);
4871
                }
4872
                else if (upStreamLine != null && downStreamSymbol != null)
4873
                {
4874
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4875
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4876
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4877

    
4878
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4879
                    {
4880
                        if (connector.get_ItemStatus() != "Active")
4881
                            continue;
4882

    
4883
                        if (connector.Id == zeroLenthConnector.Id)
4884
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4885
                    }
4886

    
4887
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4888
                    {
4889
                        if (connector.get_ItemStatus() != "Active")
4890
                            continue;
4891

    
4892
                        if (connector.Id == zeroLenthConnector.Id)
4893
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4894
                    }
4895

    
4896
                    ReleaseCOMObjects(zeroLenthConnector);
4897
                    ReleaseCOMObjects(downStreamLMSymbol);
4898
                }
4899
            }
4900

    
4901
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4902
            {
4903
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4904
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4905
                {
4906
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4907
                    if (_LMAAttribute != null)
4908
                    {
4909
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4910
                            _LMAAttribute.set_Value(value);
4911
                        else if (_LMAAttribute.get_Value() != value)
4912
                            _LMAAttribute.set_Value(value);
4913
                    }
4914

    
4915
                    _LMModelItem.Commit();
4916
                }
4917
                if (_LMModelItem != null)
4918
                    ReleaseCOMObjects(_LMModelItem);
4919
            }
4920

    
4921
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4922
            {
4923
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4924
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4925
                {
4926
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4927
                    if (_LMAAttribute != null)
4928
                    {
4929
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4930
                            _LMAAttribute.set_Value(value);
4931
                        else if (_LMAAttribute.get_Value() != value)
4932
                            _LMAAttribute.set_Value(value);
4933
                    }
4934

    
4935
                    _LMModelItem.Commit();
4936
                }
4937
                if (_LMModelItem != null)
4938
                    ReleaseCOMObjects(_LMModelItem);
4939
            }
4940
            #endregion
4941
        }
4942

    
4943
        private void InputEndBreakAttribute(EndBreak endBreak)
4944
        {
4945
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4946
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4947

    
4948
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4949
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4950
            {
4951
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4952
                if (labelPersist != null)
4953
                {
4954
                    LMRepresentation representation = labelPersist.RepresentationObject;
4955
                    if (representation != null)
4956
                    {
4957
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4958
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4959
                        string modelItemID = connector.ModelItemID;
4960
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4961
                        {
4962
                            List<string> modelItemIDs = new List<string>();
4963
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4964
                            {
4965
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4966
                                foreach (LMConnector item in symbol.Connect1Connectors)
4967
                                {
4968
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4969
                                        modelItemIDs.Add(item.ModelItemID);
4970
                                    ReleaseCOMObjects(item);
4971
                                }
4972
                                foreach (LMConnector item in symbol.Connect2Connectors)
4973
                                {
4974
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4975
                                        modelItemIDs.Add(item.ModelItemID);
4976
                                    ReleaseCOMObjects(item);
4977
                                }
4978
                                ReleaseCOMObjects(symbol);
4979
                                symbol = null;
4980
                            }
4981
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4982
                            {
4983
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4984
                                foreach (LMConnector item in symbol.Connect1Connectors)
4985
                                {
4986
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4987
                                        modelItemIDs.Add(item.ModelItemID);
4988
                                    ReleaseCOMObjects(item);
4989
                                }
4990
                                foreach (LMConnector item in symbol.Connect2Connectors)
4991
                                {
4992
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4993
                                        modelItemIDs.Add(item.ModelItemID);
4994
                                    ReleaseCOMObjects(item);
4995
                                }
4996
                                ReleaseCOMObjects(symbol);
4997
                                symbol = null;
4998
                            }
4999

    
5000
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5001
                            if (modelItemIDs.Count == 1)
5002
                            {
5003
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5004
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5005
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5006
                                {
5007
                                    bool result = false;
5008
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5009
                                    {
5010
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5011
                                            result = true;
5012
                                        ReleaseCOMObjects(loop);
5013
                                    }
5014

    
5015
                                    if (result)
5016
                                    {
5017
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5018
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5019
                                        ZeroLengthModelItem.Commit();
5020
                                    }
5021
                                    else
5022
                                    {
5023
                                        List<string> loopModelItems = new List<string>();
5024
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5025
                                        {
5026
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5027
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5028
                                            {
5029
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5030
                                                    loopModelItems.Add(loop.ModelItemID);
5031
                                                ReleaseCOMObjects(loop);
5032
                                            }
5033
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5034
                                            {
5035
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5036
                                                    loopModelItems.Add(loop.ModelItemID);
5037
                                                ReleaseCOMObjects(loop);
5038
                                            }
5039
                                            ReleaseCOMObjects(_symbol);
5040
                                            _symbol = null;
5041
                                        }
5042
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5043
                                        {
5044
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5045
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5046
                                            {
5047
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5048
                                                    loopModelItems.Add(loop.ModelItemID);
5049
                                                ReleaseCOMObjects(loop);
5050
                                            }
5051
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5052
                                            {
5053
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5054
                                                    loopModelItems.Add(loop.ModelItemID);
5055
                                                ReleaseCOMObjects(loop);
5056
                                            }
5057
                                            ReleaseCOMObjects(_symbol);
5058
                                            _symbol = null;
5059
                                        }
5060

    
5061
                                        loopModelItems = loopModelItems.Distinct().ToList();
5062
                                        if (loopModelItems.Count == 1)
5063
                                        {
5064
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5065
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5066
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5067
                                            modelItem.Commit();
5068
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5069
                                            ZeroLengthModelItem.Commit();
5070

    
5071
                                            ReleaseCOMObjects(loopModelItem);
5072
                                            loopModelItem = null;
5073
                                        }
5074
                                    }
5075
                                }
5076
                                else
5077
                                {
5078
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5079
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5080
                                    ZeroLengthModelItem.Commit();
5081
                                }
5082
                                ReleaseCOMObjects(modelItem);
5083
                                modelItem = null;
5084
                                ReleaseCOMObjects(onlyOne);
5085
                                onlyOne = null;
5086
                            }
5087
                        }
5088
                        ReleaseCOMObjects(connector);
5089
                        connector = null;
5090
                        ReleaseCOMObjects(ZeroLengthModelItem);
5091
                        ZeroLengthModelItem = null;
5092
                    }
5093
                    ReleaseCOMObjects(representation);
5094
                    representation = null;
5095
                }
5096
                ReleaseCOMObjects(labelPersist);
5097
                labelPersist = null;
5098
            }
5099
        }
5100

    
5101
        /// <summary>
5102
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5103
        /// </summary>
5104
        /// <param name="text"></param>
5105
        private void NormalTextModeling(Text text)
5106
        {
5107
            LMSymbol _LMSymbol = null;
5108

    
5109
            LMItemNote _LMItemNote = null;
5110
            LMAAttribute _LMAAttribute = null;
5111

    
5112
            double x = 0;
5113
            double y = 0;
5114
            double angle = text.ANGLE;
5115
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5116

    
5117
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5118
            text.SPPID.SPPID_X = x;
5119
            text.SPPID.SPPID_Y = y;
5120

    
5121
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5122
            if (_LMSymbol != null)
5123
            {
5124
                _LMSymbol.Commit();
5125
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5126
                if (_LMItemNote != null)
5127
                {
5128
                    _LMItemNote.Commit();
5129
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5130
                    if (_LMAAttribute != null)
5131
                    {
5132
                        _LMAAttribute.set_Value(text.VALUE);
5133
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5134
                        _LMItemNote.Commit();
5135

    
5136

    
5137
                        double[] range = null;
5138
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5139
                        {
5140
                            double[] temp = null;
5141
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5142
                            if (temp != null)
5143
                            {
5144
                                if (range == null)
5145
                                    range = temp;
5146
                                else
5147
                                {
5148
                                    range = new double[] {
5149
                                            Math.Min(range[0], temp[0]),
5150
                                            Math.Min(range[1], temp[1]),
5151
                                            Math.Max(range[2], temp[2]),
5152
                                            Math.Max(range[3], temp[3])
5153
                                        };
5154
                                }
5155
                            }
5156
                        }
5157
                        text.SPPID.Range = range;
5158

    
5159
                        if (_LMAAttribute != null)
5160
                            ReleaseCOMObjects(_LMAAttribute);
5161
                        if (_LMItemNote != null)
5162
                            ReleaseCOMObjects(_LMItemNote);
5163
                    }
5164

    
5165
                    TextCorrectModeling(text);
5166
                }
5167
            }
5168
            if (_LMSymbol != null)
5169
                ReleaseCOMObjects(_LMSymbol);
5170
        }
5171

    
5172
        private void DefaultTextModeling(string value, double x, double y)
5173
        {
5174
            LMSymbol _LMSymbol = null;
5175

    
5176
            LMItemNote _LMItemNote = null;
5177
            LMAAttribute _LMAAttribute = null;
5178

    
5179
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5180
            if (_LMSymbol != null)
5181
            {
5182
                _LMSymbol.Commit();
5183
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5184
                if (_LMItemNote != null)
5185
                {
5186
                    _LMItemNote.Commit();
5187
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5188
                    if (_LMAAttribute != null)
5189
                    {
5190
                        _LMAAttribute.set_Value(value);
5191
                        _LMItemNote.Commit();
5192

    
5193
                        if (_LMAAttribute != null)
5194
                            ReleaseCOMObjects(_LMAAttribute);
5195
                        if (_LMItemNote != null)
5196
                            ReleaseCOMObjects(_LMItemNote);
5197
                    }
5198
                }
5199
            }
5200
            if (_LMSymbol != null)
5201
                ReleaseCOMObjects(_LMSymbol);
5202
        }
5203

    
5204
        private void AssociationTextModeling(Text text)
5205
        {
5206
            LMSymbol _LMSymbol = null;
5207
            LMConnector connectedLMConnector = null;
5208
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5209
            if (owner != null && owner.GetType() == typeof(Symbol))
5210
            {
5211
                Symbol symbol = owner as Symbol;
5212
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5213
                if (_LMSymbol != null)
5214
                {
5215
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5216
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5217
                    {
5218
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5219

    
5220
                        if (mapping != null)
5221
                        {
5222
                            double x = 0;
5223
                            double y = 0;
5224

    
5225
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5226
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5227
                            Array array = new double[] { 0, x, y };
5228
                            text.SPPID.SPPID_X = x;
5229
                            text.SPPID.SPPID_Y = y;
5230
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5231
                            if (_LMLabelPersist != null)
5232
                            {
5233
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5234
                                _LMLabelPersist.Commit();
5235
                                ReleaseCOMObjects(_LMLabelPersist);
5236
                            }
5237
                        }
5238
                    }
5239
                }
5240
            }
5241
            else if (owner != null && owner.GetType() == typeof(Line))
5242
            {
5243
                Line line = owner as Line;
5244
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5245
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5246

    
5247
                if (connectedLMConnector != null)
5248
                {
5249
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5250
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5251
                    {
5252
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5253

    
5254
                        if (mapping != null)
5255
                        {
5256
                            double x = 0;
5257
                            double y = 0;
5258
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5259
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5260
                            Array array = new double[] { 0, x, y };
5261

    
5262
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5263
                            if (_LMLabelPersist != null)
5264
                            {
5265
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5266
                                _LMLabelPersist.Commit();
5267
                               
5268
                                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5269
                                if (dependency != null)
5270
                                {
5271
                                    radApp.ActiveSelectSet.RemoveAll();
5272
                                    radApp.ActiveSelectSet.Add(dependency);
5273
                                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
5274
                                    transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5275
                                    radApp.ActiveSelectSet.Transform(transform, true);
5276
                                    radApp.ActiveSelectSet.RemoveAll();
5277
                                }
5278

    
5279
                                ReleaseCOMObjects(_LMLabelPersist);
5280
                            }
5281
                        }
5282
                    }
5283
                }
5284
            }
5285
            if (_LMSymbol != null)
5286
                ReleaseCOMObjects(_LMSymbol);
5287
        }
5288

    
5289
        private void TextCorrectModeling(Text text)
5290
        {
5291
            if (text.SPPID.Range == null)
5292
                return;
5293

    
5294
            bool needRemodeling = false;
5295
            bool loop = true;
5296
            GridSetting gridSetting = GridSetting.GetInstance();
5297
            while (loop)
5298
            {
5299
                loop = false;
5300
                foreach (var overlapText in document.TEXTINFOS)
5301
                {
5302
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5303
                        continue;
5304

    
5305
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5306
                    {
5307
                        double percentX = 0;
5308
                        double percentY = 0;
5309
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5310
                        {
5311
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5312
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5313
                        }
5314
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5315
                        {
5316
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5317
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5318
                        }
5319

    
5320
                        double tempX = 0;
5321
                        double tempY = 0;
5322
                        bool overlapX = false;
5323
                        bool overlapY = false;
5324
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5325
                        if (percentX >= percentY)
5326
                        {
5327
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5328
                            double move = gridSetting.Length * count;
5329
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5330
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5331
                            needRemodeling = true;
5332
                            loop = true;
5333
                        }
5334
                        else
5335
                        {
5336
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5337
                            double move = gridSetting.Length * count;
5338
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5339
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5340
                            needRemodeling = true;
5341
                            loop = true;
5342
                        }
5343
                    }
5344
                }
5345
            }
5346
            
5347

    
5348
            if (needRemodeling)
5349
            {
5350
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5351
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5352
                text.SPPID.RepresentationId = null;
5353

    
5354
                LMItemNote _LMItemNote = null;
5355
                LMAAttribute _LMAAttribute = null;
5356
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5357
                if (_LMSymbol != null)
5358
                {
5359
                    _LMSymbol.Commit();
5360
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5361
                    if (_LMItemNote != null)
5362
                    {
5363
                        _LMItemNote.Commit();
5364
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5365
                        if (_LMAAttribute != null)
5366
                        {
5367
                            _LMAAttribute.set_Value(text.VALUE);
5368
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5369
                            _LMItemNote.Commit();
5370

    
5371
                            ReleaseCOMObjects(_LMAAttribute);
5372
                            ReleaseCOMObjects(_LMItemNote);
5373
                        }
5374
                    }
5375
                }
5376

    
5377
                ReleaseCOMObjects(symbol);
5378
                symbol = null;
5379
                ReleaseCOMObjects(_LMItemNote);
5380
                _LMItemNote = null;
5381
                ReleaseCOMObjects(_LMAAttribute);
5382
                _LMAAttribute = null;
5383
                ReleaseCOMObjects(_LMSymbol);
5384
                _LMSymbol = null;
5385
            }
5386
        }
5387

    
5388
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5389
        {
5390
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5391
            {
5392
                List<Text> allTexts = new List<Text>();
5393
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5394
                LMRepresentation representation = targetLabel.RepresentationObject;
5395
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5396
                if (targetLabel.RepresentationObject != null && symbol != null)
5397
                {
5398
                    double[] symbolRange = null;
5399
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5400
                    if (symbolRange != null)
5401
                    {
5402
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5403
                        {
5404
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5405
                            if (findText != null)
5406
                            {
5407
                                double[] range = null;
5408
                                GetSPPIDSymbolRange(labelPersist, ref range);
5409
                                findText.SPPID.Range = range;
5410
                                allTexts.Add(findText);
5411
                            }
5412

    
5413
                            ReleaseCOMObjects(labelPersist);
5414
                        }
5415

    
5416
                        if (allTexts.Count > 0)
5417
                        {
5418
                            #region Sort Text By Y
5419
                            allTexts.Sort(SortTextByY);
5420
                            int SortTextByY(Text a, Text b)
5421
                            {
5422
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5423
                            }
5424
                            #endregion
5425

    
5426
                            #region 정렬하기전 방향
5427
                            List<Text> left = new List<Text>();
5428
                            List<Text> down = new List<Text>();
5429
                            List<Text> right = new List<Text>();
5430
                            List<Text> up = new List<Text>();
5431
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5432
                            foreach (var loopText in allTexts)
5433
                            {
5434
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5435
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5436
                                double originX = 0;
5437
                                double originY = 0;
5438
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5439
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5440

    
5441
                                if (angle < 45)
5442
                                {
5443
                                    // Text 오른쪽
5444
                                    if (textCenterX > originX)
5445
                                        right.Add(loopText);
5446
                                    // Text 왼쪽
5447
                                    else
5448
                                        left.Add(loopText); 
5449
                                }
5450
                                else
5451
                                {
5452
                                    // Text 아래쪽
5453
                                    if (textCenterY > originY)
5454
                                        down.Add(loopText);
5455
                                    // Text 위쪽
5456
                                    else
5457
                                        up.Add(loopText);
5458
                                }
5459
                            }
5460
                            
5461
                            #endregion
5462

    
5463
                            foreach (var texts in sortTexts)
5464
                            {
5465
                                if (texts.Count == 0 )
5466
                                    continue;
5467
                                
5468
                                #region 첫번째 Text로 기준 맞춤
5469
                                for (int i = 0; i < texts.Count; i++)
5470
                                {
5471
                                    if (i != 0)
5472
                                    {
5473
                                        Text currentText = texts[i];
5474
                                        Text prevText = texts[i - 1];
5475
                                        double minY = prevText.SPPID.Range[1];
5476
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5477
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5478
                                        double _gapX = centerX - centerPrevX;
5479
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5480
                                        MoveText(currentText, _gapX, _gapY);
5481
                                    }
5482
                                }
5483
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5484
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5485
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5486
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5487
                                rangeMinX.Sort();
5488
                                rangeMinY.Sort();
5489
                                rangeMaxX.Sort();
5490
                                rangeMaxY.Sort();
5491
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5492
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5493
                                #endregion
5494
                                #region 정렬
5495
                                Text correctBySymbol = texts[0];
5496
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5497
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5498
                                double originX = 0;
5499
                                double originY = 0;
5500
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5501
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5502
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5503
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5504

    
5505
                                double gapX = 0;
5506
                                double gapY = 0;
5507
                                if (angle < 45)
5508
                                {
5509
                                    // Text 오른쪽
5510
                                    if (textCenterX > originX)
5511
                                    {
5512
                                        gapX = rangeMinX[0] - symbolRange[2];
5513
                                        gapY = allTextCenterY - symbolCenterY;
5514
                                    }
5515
                                    // Text 왼쪽
5516
                                    else
5517
                                    {
5518
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5519
                                        gapY = allTextCenterY - symbolCenterY;
5520
                                    }
5521
                                }
5522
                                else
5523
                                {
5524
                                    // Text 아래쪽
5525
                                    if (textCenterY > originY)
5526
                                    {
5527
                                        gapX = allTextCenterX - symbolCenterX;
5528
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5529
                                    }
5530
                                    // Text 위쪽
5531
                                    else
5532
                                    {
5533
                                        gapX = allTextCenterX - symbolCenterX;
5534
                                        gapY = rangeMinY[0] - symbolRange[3];
5535
                                    }
5536
                                }
5537

    
5538
                                foreach (var item in texts)
5539
                                {
5540
                                    MoveText(item, gapX, gapY);
5541
                                    RemodelingAssociationText(item);
5542
                                }
5543
                                #endregion
5544
                            }
5545
                        }
5546
                    }
5547
                }
5548

    
5549
                void MoveText(Text moveText, double x, double y)
5550
                {
5551
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5552
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5553
                    moveText.SPPID.Range = new double[] {
5554
                        moveText.SPPID.Range[0] - x,
5555
                        moveText.SPPID.Range[1]- y,
5556
                        moveText.SPPID.Range[2]- x,
5557
                        moveText.SPPID.Range[3]- y
5558
                    };
5559
                }
5560

    
5561
                endTexts.AddRange(allTexts);
5562

    
5563
                ReleaseCOMObjects(targetLabel);
5564
                targetLabel = null;
5565
                ReleaseCOMObjects(representation);
5566
                representation = null;
5567
            }
5568
        }
5569

    
5570
        private void RemodelingAssociationText(Text text)
5571
        {
5572
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5573
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5574
            removeLabel.Commit();
5575
            ReleaseCOMObjects(removeLabel);
5576
            removeLabel = null;
5577

    
5578
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5579
            if (owner != null && owner.GetType() == typeof(Symbol))
5580
            {
5581
                Symbol symbol = owner as Symbol;
5582
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5583
                if (_LMSymbol != null)
5584
                {
5585
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5586
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5587
                    {
5588
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5589

    
5590
                        if (mapping != null)
5591
                        {
5592
                            double x = 0;
5593
                            double y = 0;
5594

    
5595
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5596
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5597
                            if (_LMLabelPersist != null)
5598
                            {
5599
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5600
                                _LMLabelPersist.Commit();
5601
                            }
5602
                            ReleaseCOMObjects(_LMLabelPersist);
5603
                            _LMLabelPersist = null;
5604
                        }
5605
                    }
5606
                }
5607
                ReleaseCOMObjects(_LMSymbol);
5608
                _LMSymbol = null;
5609
            }
5610
        }
5611

    
5612
        /// <summary>
5613
        /// Note Modeling
5614
        /// </summary>
5615
        /// <param name="note"></param>
5616
        private void NoteModeling(Note note, List<Note> correctList)
5617
        {
5618
            LMSymbol _LMSymbol = null;
5619
            LMItemNote _LMItemNote = null;
5620
            LMAAttribute _LMAAttribute = null;
5621

    
5622
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5623
            {
5624
                double x = 0;
5625
                double y = 0;
5626

    
5627
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5628
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5629
                note.SPPID.SPPID_X = x;
5630
                note.SPPID.SPPID_Y = y;
5631

    
5632
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5633
                if (_LMSymbol != null)
5634
                {
5635
                    _LMSymbol.Commit();
5636
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5637
                    if (_LMItemNote != null)
5638
                    {
5639
                        _LMItemNote.Commit();
5640
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5641
                        if (_LMAAttribute != null)
5642
                        {
5643
                            _LMAAttribute.set_Value(note.VALUE);
5644
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5645

    
5646
                            double[] range = null;
5647
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5648
                            {
5649
                                double[] temp = null;
5650
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5651
                                if (temp != null)
5652
                                {
5653
                                    if (range == null)
5654
                                        range = temp;
5655
                                    else
5656
                                    {
5657
                                        range = new double[] {
5658
                                            Math.Min(range[0], temp[0]),
5659
                                            Math.Min(range[1], temp[1]),
5660
                                            Math.Max(range[2], temp[2]),
5661
                                            Math.Max(range[3], temp[3])
5662
                                        };
5663
                                    }
5664
                                }
5665
                            }
5666
                            if (range != null)
5667
                                correctList.Add(note);
5668
                            note.SPPID.Range = range;
5669

    
5670

    
5671
                            _LMItemNote.Commit();
5672
                        }
5673
                    }
5674
                }
5675
            }
5676

    
5677
            if (_LMAAttribute != null)
5678
                ReleaseCOMObjects(_LMAAttribute);
5679
            if (_LMItemNote != null)
5680
                ReleaseCOMObjects(_LMItemNote);
5681
            if (_LMSymbol != null)
5682
                ReleaseCOMObjects(_LMSymbol);
5683
        }
5684

    
5685
        private void NoteCorrectModeling(Note note, List<Note> endList)
5686
        {
5687
            bool needRemodeling = false;
5688
            bool loop = true;
5689
            GridSetting gridSetting = GridSetting.GetInstance();
5690
            while (loop)
5691
            {
5692
                loop = false;
5693
                foreach (var overlap in endList)
5694
                {
5695
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5696
                    {
5697
                        double tempX = 0;
5698
                        double tempY = 0;
5699
                        bool overlapX = false;
5700
                        bool overlapY = false;
5701
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5702
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5703
                        if (overlapY && angle >= 45)
5704
                        {
5705
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5706
                            double move = gridSetting.Length * count;
5707
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5708
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5709
                            needRemodeling = true;
5710
                            loop = true;
5711
                        }
5712
                        if (overlapX && angle <= 45)
5713
                        {
5714
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5715
                            double move = gridSetting.Length * count;
5716
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5717
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5718
                            needRemodeling = true;
5719
                            loop = true;
5720
                        }
5721
                    }
5722
                }
5723
            }
5724

    
5725

    
5726
            if (needRemodeling)
5727
            {
5728
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5729
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5730
                note.SPPID.RepresentationId = null;
5731

    
5732
                LMItemNote _LMItemNote = null;
5733
                LMAAttribute _LMAAttribute = null;
5734
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5735
                if (_LMSymbol != null)
5736
                {
5737
                    _LMSymbol.Commit();
5738
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5739
                    if (_LMItemNote != null)
5740
                    {
5741
                        _LMItemNote.Commit();
5742
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5743
                        if (_LMAAttribute != null)
5744
                        {
5745
                            _LMAAttribute.set_Value(note.VALUE);
5746
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5747
                            _LMItemNote.Commit();
5748

    
5749
                            ReleaseCOMObjects(_LMAAttribute);
5750
                            ReleaseCOMObjects(_LMItemNote);
5751
                        }
5752
                    }
5753
                }
5754

    
5755
                ReleaseCOMObjects(symbol);
5756
                symbol = null;
5757
                ReleaseCOMObjects(_LMItemNote);
5758
                _LMItemNote = null;
5759
                ReleaseCOMObjects(_LMAAttribute);
5760
                _LMAAttribute = null;
5761
                ReleaseCOMObjects(_LMSymbol);
5762
                _LMSymbol = null;
5763
            }
5764

    
5765
            endList.Add(note);
5766
        }
5767

    
5768
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5769
        {
5770
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5771
            if (modelItem != null)
5772
            {
5773
                foreach (LMRepresentation rep in modelItem.Representations)
5774
                {
5775
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5776
                    {
5777
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5778
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5779
                        {
5780
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5781
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5782
                            if (modelItemIds.Count == 1)
5783
                            {
5784
                                string joinModelItemId = modelItemIds[0];
5785
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5786
                                if (survivorId != null)
5787
                                    break;
5788
                            }
5789
                        }
5790
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5791
                        {
5792
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5793
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5794
                            if (modelItemIds.Count == 1)
5795
                            {
5796
                                string joinModelItemId = modelItemIds[0];
5797
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5798
                                if (survivorId != null)
5799
                                    break;
5800
                            }
5801
                        }
5802
                    }
5803
                }
5804
            }
5805
        }
5806

    
5807
        /// <summary>
5808
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5809
        /// </summary>
5810
        /// <param name="x"></param>
5811
        /// <param name="y"></param>
5812
        /// <param name="originX"></param>
5813
        /// <param name="originY"></param>
5814
        /// <param name="SPPIDLabelLocation"></param>
5815
        /// <param name="location"></param>
5816
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5817
        {
5818
            if (location == Location.None)
5819
            {
5820
                x = originX;
5821
                y = originY;
5822
            }
5823
            else
5824
            {
5825
                if (location.HasFlag(Location.Center))
5826
                {
5827
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5828
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5829
                }
5830

    
5831
                if (location.HasFlag(Location.Left))
5832
                    x = SPPIDLabelLocation.X1;
5833
                else if (location.HasFlag(Location.Right))
5834
                    x = SPPIDLabelLocation.X2;
5835

    
5836
                if (location.HasFlag(Location.Down))
5837
                    y = SPPIDLabelLocation.Y1;
5838
                else if (location.HasFlag(Location.Up))
5839
                    y = SPPIDLabelLocation.Y2;
5840
            }
5841
        }
5842

    
5843
        /// <summary>
5844
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5845
        /// 1. Angle Valve
5846
        /// 2. 3개로 이루어진 Symbol Group
5847
        /// </summary>
5848
        /// <returns></returns>
5849
        private List<Symbol> GetPrioritySymbol()
5850
        {
5851
            DataTable symbolTable = document.SymbolTable;
5852
            // List에 순서대로 쌓는다.
5853
            List<Symbol> symbols = new List<Symbol>();
5854

    
5855
            // Angle Valve 부터
5856
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5857
            {
5858
                if (!symbols.Contains(symbol))
5859
                {
5860
                    double originX = 0;
5861
                    double originY = 0;
5862

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

    
5867
                    SlopeType slopeType1 = SlopeType.None;
5868
                    SlopeType slopeType2 = SlopeType.None;
5869
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5870
                    {
5871
                        double connectorX = 0;
5872
                        double connectorY = 0;
5873
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5874
                        if (slopeType1 == SlopeType.None)
5875
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5876
                        else
5877
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5878
                    }
5879

    
5880
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5881
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5882
                        symbols.Add(symbol);
5883
                }
5884
            }
5885

    
5886
            List<Symbol> tempSymbols = new List<Symbol>();
5887
            // Conn 갯수 기준
5888
            foreach (var item in document.SYMBOLS)
5889
            {
5890
                if (!symbols.Contains(item))
5891
                    tempSymbols.Add(item);
5892
            }
5893
            tempSymbols.Sort(SortSymbolPriority);
5894
            symbols.AddRange(tempSymbols);
5895

    
5896
            return symbols;
5897
        }
5898

    
5899
        private void SetPriorityLine(List<Line> lines)
5900
        {
5901
            lines.Sort(SortLinePriority);
5902

    
5903
            int SortLinePriority(Line a, Line b)
5904
            {
5905
                // Branch 없는것부터
5906
                int branchRetval = CompareBranchLine(a, b);
5907
                if (branchRetval != 0)
5908
                {
5909
                    return branchRetval;
5910
                }
5911
                else
5912
                {
5913
                    // Symbol 연결 갯수
5914
                    int connSymbolRetval = CompareConnSymbol(a, b);
5915
                    if (connSymbolRetval != 0)
5916
                    {
5917
                        return connSymbolRetval;
5918
                    }
5919
                    else
5920
                    {
5921
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5922
                        int connItemRetval = CompareConnItem(a, b);
5923
                        if (connItemRetval != 0)
5924
                        {
5925
                            return connItemRetval;
5926
                        }
5927
                        else
5928
                        {
5929
                            // ConnectedItem이 없는것
5930
                            int noneConnRetval = CompareNoneConn(a, b);
5931
                            if (noneConnRetval != 0)
5932
                            {
5933
                                return noneConnRetval;
5934
                            }
5935
                            else
5936
                            {
5937

    
5938
                            }
5939
                        }
5940
                    }
5941
                }
5942

    
5943
                return 0;
5944
            }
5945

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

    
5952
                List<Connector> connectorsB = b.CONNECTORS
5953
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5954
                    .ToList();
5955

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

    
5960
            int CompareConnSymbol(Line a, Line b)
5961
            {
5962
                List<Connector> connectorsA = a.CONNECTORS
5963
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5964
                    .ToList();
5965

    
5966
                List<Connector> connectorsB = b.CONNECTORS
5967
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5968
                    .ToList();
5969

    
5970
                // 오름차순
5971
                return connectorsB.Count.CompareTo(connectorsA.Count);
5972
            }
5973

    
5974
            int CompareConnItem(Line a, Line b)
5975
            {
5976
                List<Connector> connectorsA = a.CONNECTORS
5977
                    .Where(conn => conn.ConnectedObject != null && 
5978
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5979
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5980
                    .ToList();
5981

    
5982
                List<Connector> connectorsB = b.CONNECTORS
5983
                    .Where(conn => conn.ConnectedObject != null &&
5984
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5985
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5986
                    .ToList();
5987

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

    
5992
            int CompareBranchLine(Line a, Line b)
5993
            {
5994
                List<Connector> connectorsA = a.CONNECTORS
5995
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5996
                    .ToList();
5997
                List<Connector> connectorsB = b.CONNECTORS
5998
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5999
                    .ToList();
6000

    
6001
                // 내림차순
6002
                return connectorsA.Count.CompareTo(connectorsB.Count);
6003
            }
6004

    
6005
            int CompareNoneConn(Line a, Line b)
6006
            {
6007
                List<Connector> connectorsA = a.CONNECTORS
6008
                    .Where(conn => conn.ConnectedObject == null)
6009
                    .ToList();
6010

    
6011
                List<Connector> connectorsB = b.CONNECTORS
6012
                    .Where(conn => conn.ConnectedObject == null)
6013
                    .ToList();
6014

    
6015
                // 오름차순
6016
                return connectorsB.Count.CompareTo(connectorsA.Count);
6017
            }
6018
        }
6019

    
6020
        private void SortText(List<Text> texts)
6021
        {
6022
            texts.Sort(Sort);
6023

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

    
6037
            int CompareY(Text a, Text b)
6038
            {
6039
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6040
            }
6041

    
6042
            int CompareX(Text a, Text b)
6043
            {
6044
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6045
            }
6046
        }
6047
        private void SortNote(List<Note> notes)
6048
        {
6049
            notes.Sort(Sort);
6050

    
6051
            int Sort(Note a, Note b)
6052
            {
6053
                int yRetval = CompareY(a, b);
6054
                if (yRetval != 0)
6055
                {
6056
                    return yRetval;
6057
                }
6058
                else
6059
                {
6060
                    return CompareX(a, b);
6061
                }
6062
            }
6063

    
6064
            int CompareY(Note a, Note b)
6065
            {
6066
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6067
            }
6068

    
6069
            int CompareX(Note a, Note b)
6070
            {
6071
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6072
            }
6073
        }
6074

    
6075
        private void SortBranchLines()
6076
        {
6077
            BranchLines.Sort(SortBranchLine);
6078
            int SortBranchLine(Line a, Line b)
6079
            {
6080
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6081
                 x.ConnectedObject.GetType() == typeof(Line) &&
6082
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6083
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6084

    
6085
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6086
                 x.ConnectedObject.GetType() == typeof(Line) &&
6087
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6088
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6089

    
6090
                // 내림차순
6091
                return countA.CompareTo(countB);
6092
            }
6093
        }
6094

    
6095
        private static int SortSymbolPriority(Symbol a, Symbol b)
6096
        {
6097
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6098
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6099
            int retval = countB.CompareTo(countA);
6100
            if (retval != 0)
6101
                return retval;
6102
            else
6103
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6104
        }
6105

    
6106
        private string GetSPPIDFileName(LMModelItem modelItem)
6107
        {
6108
            string symbolPath = null;
6109
            foreach (LMRepresentation rep in modelItem.Representations)
6110
            {
6111
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6112
                {
6113
                    symbolPath = rep.get_FileName();
6114
                    break;
6115
                }
6116
            }
6117
            return symbolPath;
6118
        }
6119

    
6120
        private string GetSPPIDFileName(string modelItemId)
6121
        {
6122
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6123
            string symbolPath = null;
6124
            foreach (LMRepresentation rep in modelItem.Representations)
6125
            {
6126
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6127
                {
6128
                    symbolPath = rep.get_FileName();
6129
                    break;
6130
                }
6131
            }
6132
            ReleaseCOMObjects(modelItem);
6133
            return symbolPath;
6134
        }
6135

    
6136
        /// <summary>
6137
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6138
        /// </summary>
6139
        /// <param name="graphicOID"></param>
6140
        /// <param name="milliseconds"></param>
6141
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6142
        {
6143
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6144
            {
6145
                double minX = 0;
6146
                double minY = 0;
6147
                double maxX = 0;
6148
                double maxY = 0;
6149
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6150
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6151

    
6152
                Thread.Sleep(milliseconds);
6153
            }
6154
        }
6155

    
6156
        /// <summary>
6157
        /// ComObject를 Release
6158
        /// </summary>
6159
        /// <param name="objVars"></param>
6160
        public void ReleaseCOMObjects(params object[] objVars)
6161
        {
6162
            if (objVars != null)
6163
            {
6164
                int intNewRefCount = 0;
6165
                foreach (object obj in objVars)
6166
                {
6167
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6168
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6169
                }
6170
            }
6171
        }
6172

    
6173
        /// IDisposable 구현
6174
        ~AutoModeling()
6175
        {
6176
            this.Dispose(false);
6177
        }
6178

    
6179
        private bool disposed;
6180
        public void Dispose()
6181
        {
6182
            this.Dispose(true);
6183
            GC.SuppressFinalize(this);
6184
        }
6185

    
6186
        protected virtual void Dispose(bool disposing)
6187
        {
6188
            if (this.disposed) return;
6189
            if (disposing)
6190
            {
6191
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6192
            }
6193
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6194
            this.disposed = true;
6195
        }
6196
    }
6197
}
클립보드 이미지 추가 (최대 크기: 500 MB)