프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 94ac8af8

이력 | 보기 | 이력해설 | 다운로드 (291 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
        }
972
        private void RunCorrectAssociationText()
973
        {
974
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
975
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
976
            List<Text> endTexts = new List<Text>();
977
            foreach (var item in document.TEXTINFOS)
978
            {
979
                try
980
                {
981
                    if (item.ASSOCIATION && !endTexts.Contains(item))
982
                        AssociationTextCorrectModeling(item, endTexts);
983
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
984
                }
985
                catch (Exception ex)
986
                {
987
                    Log.Write("Error in RunCorrectAssociationText");
988
                    Log.Write("UID : " + item.UID);
989
                    Log.Write(ex.Message);
990
                    Log.Write(ex.StackTrace);
991
                }
992
                
993
            }
994

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

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

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

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

    
1089
                        drawingAttributeDT.Dispose();
1090
                    }
1091

    
1092
                    ReleaseCOMObjects(drawing);
1093
                }
1094

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

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

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

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

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

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

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

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

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

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

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

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

    
1236
            LMSymbol _LMSymbol = null;
1237

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

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

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

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

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

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

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

    
1278
            if (_LMSymbol != null)
1279
            {
1280
                _LMSymbol.Commit();
1281

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

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

    
1303

    
1304
                }
1305

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

    
1310
                foreach (var item in symbol.ChildSymbols)
1311
                    CreateChildSymbol(item, _LMSymbol, symbol);
1312

    
1313
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1314
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1315

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

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

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

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

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

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

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

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

    
1447
            return info;
1448
        }
1449

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

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

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

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

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

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

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

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

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

    
1536
            double SPPIDgapX = gapX * percentX;
1537
            double SPPIDgapY = gapY * percentY;
1538

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

    
1554
            ReleaseCOMObjects(_TargetItem);
1555
        }
1556

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

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

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

    
1599
            ReleaseCOMObjects(_TargetItem);
1600
        }
1601

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

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

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

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

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

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

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

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

    
1744
                foreach (var childSymbol in symbol.ChildSymbols)
1745
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1746
            }
1747

    
1748
            range = tempRange;
1749
        }
1750

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

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

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

    
1785
                ReleaseCOMObjects(_ChildSymbol);
1786
            }
1787
        }
1788

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

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

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

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

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

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

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

    
1882
                                        if (result)
1883
                                            break;
1884
                                    }
1885

    
1886
                                    if (result)
1887
                                        break;
1888
                                }
1889
                            }
1890

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

    
1896
                        ReleaseCOMObjects(_TargetItem);
1897
                    }
1898
                }
1899
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1900
                {
1901
                    Line targetLine = targetItem as Line;
1902
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1903
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1904
                    if (connectedLMConnector != null)
1905
                    {
1906
                        // Target Item에 Label의 Attribute Input
1907
                        InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1908

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

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

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

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

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

    
1949
            // Mirror 계산
1950
            if (equipment.FLIP == 1)
1951
            {
1952
                mirror = 1;
1953
                if (angle == Math.PI || angle == 0)
1954
                    angle += Math.PI;
1955
            }
1956

    
1957
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1958

    
1959
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1960
            if (connector != null)
1961
            {
1962
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1963
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1964
                if (connEquipment != null)
1965
                {
1966
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1967
                        EquipmentModeling(connEquipment);
1968

    
1969
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1970
                    {
1971
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1972
                        if (targetItem != null)
1973
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1974
                        else
1975
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1976
                    }
1977
                    else
1978
                    {
1979
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1980
                    }
1981
                }
1982
                else if (connVendorPackage != null)
1983
                {
1984
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1985
                    {
1986
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1987
                        if (targetItem != null)
1988
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1989
                        else
1990
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1991
                    }
1992
                }
1993
                else
1994
                {
1995
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1996
                }
1997
            }
1998
            else
1999
            {
2000
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2001
            }
2002

    
2003
            if (_LMSymbol != null)
2004
            {
2005
                _LMSymbol.Commit();
2006
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2007
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
2008
                ReleaseCOMObjects(_LMSymbol);
2009
            }
2010

    
2011
            if (targetItem != null)
2012
            {
2013
                ReleaseCOMObjects(targetItem);
2014
            }
2015

    
2016
            ReleaseCOMObjects(_LMSymbol);
2017
        }
2018

    
2019
        private void VendorPackageModeling(VendorPackage vendorPackage)
2020
        {
2021
            ETCSetting setting = ETCSetting.GetInstance();
2022
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2023
            {
2024
                string symbolPath = setting.VendorPackageSymbolPath;
2025
                double x = vendorPackage.SPPID.ORIGINAL_X;
2026
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2027

    
2028
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2029
                if (symbol != null)
2030
                {
2031
                    symbol.Commit();
2032
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2033
                }
2034

    
2035
                ReleaseCOMObjects(symbol);
2036
                symbol = null;
2037
            }
2038
        }
2039

    
2040
        /// <summary>
2041
        /// 첫 진입점
2042
        /// </summary>
2043
        /// <param name="symbol"></param>
2044
        private void SymbolModelingBySymbol(Symbol symbol)
2045
        {
2046
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2047
            List<object> endObjects = new List<object>();
2048
            endObjects.Add(symbol);
2049

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

    
2076
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2077
        {
2078
            foreach (var connector in symbol.CONNECTORS)
2079
            {
2080
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2081
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2082
                {
2083
                    if (!endObjects.Contains(connItem))
2084
                    {
2085
                        endObjects.Add(connItem);
2086
                        if (connItem.GetType() == typeof(Symbol))
2087
                        {
2088
                            Symbol connSymbol = connItem as Symbol;
2089
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2090
                            {
2091
                                SymbolModeling(connSymbol, symbol);
2092
                            }
2093
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2094
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2095
                        }
2096
                        else if (connItem.GetType() == typeof(Line))
2097
                        {
2098
                            Line connLine = connItem as Line;
2099
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2100
                        }
2101
                    }
2102
                }
2103
            }
2104
        }
2105

    
2106
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2107
        {
2108
            foreach (var connector in line.CONNECTORS)
2109
            {
2110
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2111
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2112
                {
2113
                    if (!endObjects.Contains(connItem))
2114
                    {
2115
                        endObjects.Add(connItem);
2116
                        if (connItem.GetType() == typeof(Symbol))
2117
                        {
2118
                            Symbol connSymbol = connItem as Symbol;
2119
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2120
                            {
2121
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2122
                                int branchCount = 0;
2123
                                if (connLine != null)
2124
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2125

    
2126
                                List<Symbol> group = new List<Symbol>();
2127
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2128
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2129
                                List<Symbol> endModelingGroup = new List<Symbol>();
2130
                                if (priority != null)
2131
                                {
2132
                                    SymbolGroupModeling(priority, group);
2133

    
2134
                                    // Range 겹치는지 확인해야함
2135
                                    double[] prevRange = null;
2136
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2137
                                    double[] groupRange = null;
2138
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2139

    
2140
                                    double distanceX = 0;
2141
                                    double distanceY = 0;
2142
                                    bool overlapX = false;
2143
                                    bool overlapY = false;
2144
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2145
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2146
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2147
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2148
                                    {
2149
                                        RemoveSymbol(group);
2150
                                        foreach (var _temp in group)
2151
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2152

    
2153
                                        SymbolGroupModeling(priority, group);
2154
                                    }
2155
                                    else if (branchCount > 0)
2156
                                    {
2157
                                        LMConnector _connector = JustLineModeling(connLine);
2158
                                        if (_connector != null)
2159
                                        {
2160
                                            double distance = GetConnectorDistance(_connector);
2161
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2162
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2163
                                            _connector.Commit();
2164
                                            ReleaseCOMObjects(_connector);
2165
                                            _connector = null;
2166
                                            if (cellCount < branchCount + 1)
2167
                                            {
2168
                                                int moveCount = branchCount - cellCount;
2169
                                                RemoveSymbol(group);
2170
                                                foreach (var _temp in group)
2171
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2172

    
2173
                                                SymbolGroupModeling(priority, group);
2174
                                            }
2175
                                        }
2176
                                    }
2177
                                }
2178
                                else
2179
                                {
2180
                                    SymbolModeling(connSymbol, null);
2181
                                    // Range 겹치는지 확인해야함
2182
                                    double[] prevRange = null;
2183
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2184
                                    double[] connRange = null;
2185
                                    GetSPPIDSymbolRange(connSymbol, ref connRange, bForGraphic: true);
2186

    
2187
                                    double distanceX = 0;
2188
                                    double distanceY = 0;
2189
                                    bool overlapX = false;
2190
                                    bool overlapY = false;
2191
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2192
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2193
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2194
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2195
                                    {
2196
                                        RemoveSymbol(connSymbol);
2197
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2198

    
2199
                                        SymbolModeling(connSymbol, null);
2200
                                    }
2201
                                    else if (branchCount > 0)
2202
                                    {
2203
                                        LMConnector _connector = JustLineModeling(connLine);
2204
                                        if (_connector != null)
2205
                                        {
2206
                                            double distance = GetConnectorDistance(_connector);
2207
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2208
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2209
                                            _connector.Commit();
2210
                                            ReleaseCOMObjects(_connector);
2211
                                            _connector = null;
2212
                                            if (cellCount < branchCount + 1)
2213
                                            {
2214
                                                int moveCount = branchCount - cellCount;
2215
                                                RemoveSymbol(group);
2216
                                                foreach (var _temp in group)
2217
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2218

    
2219
                                                SymbolGroupModeling(priority, group);
2220
                                            }
2221
                                        }
2222
                                    }
2223
                                }
2224
                            }
2225
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2226
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2227
                        }
2228
                        else if (connItem.GetType() == typeof(Line))
2229
                        {
2230
                            Line connLine = connItem as Line;
2231
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2232
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2233
                        }
2234
                    }
2235
                }
2236
            }
2237
        }
2238

    
2239
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2240
        {
2241
            List<Symbol> endModelingGroup = new List<Symbol>();
2242
            SymbolModeling(firstSymbol, null);
2243
            endModelingGroup.Add(firstSymbol);
2244
            while (endModelingGroup.Count != group.Count)
2245
            {
2246
                foreach (var _symbol in group)
2247
                {
2248
                    if (!endModelingGroup.Contains(_symbol))
2249
                    {
2250
                        foreach (var _connector in _symbol.CONNECTORS)
2251
                        {
2252
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2253
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2254
                            {
2255
                                SymbolModeling(_symbol, _connSymbol);
2256
                                endModelingGroup.Add(_symbol);
2257
                                break;
2258
                            }
2259
                        }
2260
                    }
2261
                }
2262
            }
2263
        }
2264

    
2265
        /// <summary>
2266
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2267
        /// </summary>
2268
        /// <param name="childSymbol"></param>
2269
        /// <param name="parentSymbol"></param>
2270
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2271
        {
2272
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2273
            double x1 = 0;
2274
            double x2 = 0;
2275
            double y1 = 0;
2276
            double y2 = 0;
2277
            symbol2d.Range(out x1, out y1, out x2, out y2);
2278

    
2279
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2280
            if (_LMSymbol != null)
2281
            {
2282
                _LMSymbol.Commit();
2283
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2284
                foreach (var item in childSymbol.ChildSymbols)
2285
                    CreateChildSymbol(item, _LMSymbol, parent);
2286
            }
2287

    
2288

    
2289
            ReleaseCOMObjects(_LMSymbol);
2290
        }
2291
        double index = 0;
2292
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2293
        {
2294
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2295
                return;
2296

    
2297
            List<Line> group = new List<Line>();
2298
            GetConnectedLineGroup(line, group);
2299
            LineCoordinateCorrection(group);
2300

    
2301
            foreach (var groupLine in group)
2302
            {
2303
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2304
                {
2305
                    BranchLines.Add(groupLine);
2306
                    continue;
2307
                }
2308

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

    
2382
                            placeRunInputs.AddPoint(x, y);
2383

    
2384
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2385
                            {
2386
                                index += 0.01;
2387
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2388
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2389
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2390
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2391
                                else
2392
                                {
2393
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2394
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2395
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2396
                                    else
2397
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2398
                                }
2399
                            }
2400
                        }
2401
                    }
2402
                }
2403

    
2404
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2405
                if (_lMConnector != null)
2406
                {
2407
                    _lMConnector.Commit();
2408
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2409

    
2410
                    bool bRemodelingStart = false;
2411
                    if (_LMSymbolStart != null)
2412
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2413
                    bool bRemodelingEnd = false;
2414
                    if (_LMSymbolEnd != null)
2415
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2416

    
2417
                    if (bRemodelingStart || bRemodelingEnd)
2418
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2419

    
2420
                    FlowMarkModeling(groupLine);
2421

    
2422
                    ReleaseCOMObjects(_lMConnector);
2423

    
2424
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2425
                    if (modelItem != null)
2426
                    {
2427
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2428
                        if (attribute != null)
2429
                            attribute.set_Value("End 1 is upstream (Inlet)");
2430
                        modelItem.Commit();
2431
                    }
2432
                    ReleaseCOMObjects(modelItem);
2433
                    modelItem = null;
2434
                }
2435
                else if (!isBranchModeling)
2436
                {
2437
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2438
                }
2439

    
2440
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2441
                x.ConnectedObject != null &&
2442
                x.ConnectedObject.GetType() == typeof(Line) &&
2443
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2444
                .Select(x => x.ConnectedObject)
2445
                .ToList();
2446

    
2447
                foreach (var item in removeLines)
2448
                    RemoveLineForModeling(item as Line);
2449

    
2450
                ReleaseCOMObjects(_LMAItem);
2451
                _LMAItem = null;
2452
                ReleaseCOMObjects(placeRunInputs);
2453
                placeRunInputs = null;
2454
                ReleaseCOMObjects(_LMSymbolStart);
2455
                _LMSymbolStart = null;
2456
                ReleaseCOMObjects(_LMSymbolEnd);
2457
                _LMSymbolEnd = null;
2458

    
2459
                if (isBranchModeling && BranchLines.Contains(groupLine))
2460
                    BranchLines.Remove(groupLine);
2461
            }
2462
        }
2463

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

    
2525
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2526
            if (_lMConnector != null)
2527
                _lMConnector.Commit();
2528

    
2529
            ReleaseCOMObjects(_LMAItem);
2530
            _LMAItem = null;
2531
            ReleaseCOMObjects(placeRunInputs);
2532
            placeRunInputs = null;
2533
            ReleaseCOMObjects(_LMSymbolStart);
2534
            _LMSymbolStart = null;
2535
            ReleaseCOMObjects(_LMSymbolEnd);
2536
            _LMSymbolEnd = null;
2537

    
2538
            return _lMConnector;
2539
        }
2540

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

    
2569
                ReleaseCOMObjects(modelItem);
2570
            }
2571
        }
2572

    
2573
        private void RemoveLine(Line line)
2574
        {
2575
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2576
            if (modelItem != null)
2577
            {
2578
                foreach (LMRepresentation rep in modelItem.Representations)
2579
                {
2580
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2581
                        _placement.PIDRemovePlacement(rep);
2582
                }
2583
                ReleaseCOMObjects(modelItem);
2584
            }
2585
            line.SPPID.ModelItemId = null;
2586
        }
2587

    
2588
        private void GetConnectedLineGroup(Line line, List<Line> group)
2589
        {
2590
            if (!group.Contains(line))
2591
                group.Add(line);
2592
            foreach (var connector in line.CONNECTORS)
2593
            {
2594
                if (connector.ConnectedObject != null &&
2595
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2596
                    !group.Contains(connector.ConnectedObject) &&
2597
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2598
                {
2599
                    Line connLine = connector.ConnectedObject as Line;
2600
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2601
                    {
2602
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2603
                            group.Insert(0, connLine);
2604
                        else
2605
                            group.Add(connLine);
2606
                        GetConnectedLineGroup(connLine, group);
2607
                    }
2608
                }
2609
            }
2610
        }
2611

    
2612
        private void LineCoordinateCorrection(List<Line> group)
2613
        {
2614
            // 순서대로 전 Item 기준 정렬
2615
            LineCoordinateCorrectionByStart(group);
2616

    
2617
            // 역으로 심볼이 있을 경우 좌표 보정
2618
            LineCoordinateCorrectionForLastLine(group);
2619
        }
2620

    
2621
        private void LineCoordinateCorrectionByStart(List<Line> group)
2622
        {
2623
            for (int i = 0; i < group.Count; i++)
2624
            {
2625
                Line line = group[i];
2626
                if (i == 0)
2627
                {
2628
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2629
                    if (symbolConnector != null)
2630
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2631
                }
2632
                else if (i != 0)
2633
                {
2634
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2635
                }
2636
            }
2637
        }
2638

    
2639
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2640
        {
2641
            Line checkLine = group[group.Count - 1];
2642
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2643
            if (lastSymbolConnector != null)
2644
            {
2645
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2646
                for (int i = group.Count - 2; i >= 0; i--)
2647
                {
2648
                    Line line = group[i + 1];
2649
                    Line prevLine = group[i];
2650

    
2651
                    // 같으면 보정
2652
                    if (line.SlopeType == prevLine.SlopeType)
2653
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2654
                    else
2655
                    {
2656
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2657
                        {
2658
                            double prevX = 0;
2659
                            double prevY = 0;
2660
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2661
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2662

    
2663
                            double x = 0;
2664
                            double y = 0;
2665
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2666
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2667
                        }
2668
                        else if (line.SlopeType == SlopeType.VERTICAL)
2669
                        {
2670
                            double prevX = 0;
2671
                            double prevY = 0;
2672
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2673
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2674

    
2675
                            double x = 0;
2676
                            double y = 0;
2677
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2678
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2679
                        }
2680
                        break;
2681
                    }
2682
                }
2683
            }
2684
        }
2685

    
2686
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2687
        {
2688
            double x = 0;
2689
            double y = 0;
2690
            if (connItem.GetType() == typeof(Symbol))
2691
            {
2692
                Symbol targetSymbol = connItem as Symbol;
2693
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2694
                if (targetConnector != null)
2695
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2696
                else
2697
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2698
            }
2699
            else if (connItem.GetType() == typeof(Line))
2700
            {
2701
                Line targetLine = connItem as Line;
2702
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2703
            }
2704

    
2705
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2706
        }
2707

    
2708
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2709
        {
2710
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2711
            int index = line.CONNECTORS.IndexOf(connector);
2712
            if (index == 0)
2713
            {
2714
                line.SPPID.START_X = x;
2715
                line.SPPID.START_Y = y;
2716
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2717
                    line.SPPID.END_Y = y;
2718
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2719
                    line.SPPID.END_X = x;
2720
            }
2721
            else
2722
            {
2723
                line.SPPID.END_X = x;
2724
                line.SPPID.END_Y = y;
2725
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2726
                    line.SPPID.START_Y = y;
2727
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2728
                    line.SPPID.START_X = x;
2729
            }
2730
        }
2731

    
2732
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2733
        {
2734
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2735
            int index = line.CONNECTORS.IndexOf(connector);
2736
            if (index == 0)
2737
            {
2738
                line.SPPID.START_X = x;
2739
                if (line.SlopeType == SlopeType.VERTICAL)
2740
                    line.SPPID.END_X = x;
2741
            }
2742
            else
2743
            {
2744
                line.SPPID.END_X = x;
2745
                if (line.SlopeType == SlopeType.VERTICAL)
2746
                    line.SPPID.START_X = x;
2747
            }
2748
        }
2749

    
2750
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2751
        {
2752
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2753
            int index = line.CONNECTORS.IndexOf(connector);
2754
            if (index == 0)
2755
            {
2756
                line.SPPID.START_Y = y;
2757
                if (line.SlopeType == SlopeType.HORIZONTAL)
2758
                    line.SPPID.END_Y = y;
2759
            }
2760
            else
2761
            {
2762
                line.SPPID.END_Y = y;
2763
                if (line.SlopeType == SlopeType.HORIZONTAL)
2764
                    line.SPPID.START_Y = y;
2765
            }
2766
        }
2767

    
2768
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2769
        {
2770
            if (symbol != null)
2771
            {
2772
                string repID = symbol.AsLMRepresentation().Id;
2773
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2774
                string lineUID = line.UID;
2775

    
2776
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2777
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2778
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2779

    
2780
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2781
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2782
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2783

    
2784
                if (startSpecBreak != null || startEndBreak != null)
2785
                    result = true;
2786
            }
2787
        }
2788

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

    
2815
            List<double[]> vertices = new List<double[]>();
2816
            for (int i = 1; i <= verticesCount; i++)
2817
            {
2818
                double x = 0;
2819
                double y = 0;
2820
                lineStringGeometry.GetVertex(i, ref x, ref y);
2821
                vertices.Add(new double[] { x, y });
2822
            }
2823

    
2824
            for (int i = 0; i < vertices.Count; i++)
2825
            {
2826
                double[] points = vertices[i];
2827
                // 시작 심볼이 있고 첫번째 좌표일 때
2828
                if (startSymbol != null && i == 0)
2829
                {
2830
                    if (bStart)
2831
                    {
2832
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2833
                        if (slopeType == SlopeType.HORIZONTAL)
2834
                            placeRunInputs.AddPoint(points[0], -0.1);
2835
                        else if (slopeType == SlopeType.VERTICAL)
2836
                            placeRunInputs.AddPoint(-0.1, points[1]);
2837
                        else
2838
                            placeRunInputs.AddPoint(points[0], -0.1);
2839

    
2840
                        placeRunInputs.AddPoint(points[0], points[1]);
2841
                    }
2842
                    else
2843
                    {
2844
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2845
                    }
2846
                }
2847
                // 마지막 심볼이 있고 마지막 좌표일 때
2848
                else if (endSymbol != null && i == vertices.Count - 1)
2849
                {
2850
                    if (bEnd)
2851
                    {
2852
                        placeRunInputs.AddPoint(points[0], points[1]);
2853

    
2854
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2855
                        if (slopeType == SlopeType.HORIZONTAL)
2856
                            placeRunInputs.AddPoint(points[0], -0.1);
2857
                        else if (slopeType == SlopeType.VERTICAL)
2858
                            placeRunInputs.AddPoint(-0.1, points[1]);
2859
                        else
2860
                            placeRunInputs.AddPoint(points[0], -0.1);
2861
                    }
2862
                    else
2863
                    {
2864
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2865
                    }
2866
                }
2867
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2868
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2869
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2870
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2871
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2872
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2873
                else
2874
                    placeRunInputs.AddPoint(points[0], points[1]);
2875
            }
2876

    
2877
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2878
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2879

    
2880
            ReleaseCOMObjects(placeRunInputs);
2881
            ReleaseCOMObjects(_LMAItem);
2882
            ReleaseCOMObjects(modelItem);
2883

    
2884
            if (newConnector != null)
2885
            {
2886
                newConnector.Commit();
2887
                if (startSymbol != null && bStart)
2888
                {
2889
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2890
                    placeRunInputs = new PlaceRunInputs();
2891
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2892
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2893
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2894
                    if (_LMConnector != null)
2895
                    {
2896
                        _LMConnector.Commit();
2897
                        RemoveConnectorForReModelingLine(newConnector);
2898
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2899
                        ReleaseCOMObjects(_LMConnector);
2900
                    }
2901
                    ReleaseCOMObjects(placeRunInputs);
2902
                    ReleaseCOMObjects(_LMAItem);
2903
                }
2904

    
2905
                if (endSymbol != null && bEnd)
2906
                {
2907
                    if (startSymbol != null)
2908
                    {
2909
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2910
                        newConnector = dicVertices.First().Key;
2911
                    }
2912

    
2913
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2914
                    placeRunInputs = new PlaceRunInputs();
2915
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2916
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2917
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2918
                    if (_LMConnector != null)
2919
                    {
2920
                        _LMConnector.Commit();
2921
                        RemoveConnectorForReModelingLine(newConnector);
2922
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2923
                        ReleaseCOMObjects(_LMConnector);
2924
                    }
2925
                    ReleaseCOMObjects(placeRunInputs);
2926
                    ReleaseCOMObjects(_LMAItem);
2927
                }
2928

    
2929
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2930
                ReleaseCOMObjects(newConnector);
2931
            }
2932

    
2933
            ReleaseCOMObjects(modelItem);
2934
        }
2935

    
2936
        /// <summary>
2937
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2938
        /// </summary>
2939
        /// <param name="connector"></param>
2940
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2941
        {
2942
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2943
            foreach (var item in dicVertices)
2944
            {
2945
                if (item.Value.Count == 2)
2946
                {
2947
                    bool result = false;
2948
                    foreach (var point in item.Value)
2949
                    {
2950
                        if (point[0] < 0 || point[1] < 0)
2951
                        {
2952
                            result = true;
2953
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2954
                            break;
2955
                        }
2956
                    }
2957

    
2958
                    if (result)
2959
                        break;
2960
                }
2961
            }
2962
            foreach (var item in dicVertices)
2963
                ReleaseCOMObjects(item.Key);
2964
        }
2965

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

    
2991
                            if (child != null)
2992
                                break;
2993
                        }
2994

    
2995
                        if (child != null)
2996
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2997
                    }
2998

    
2999
                    break;
3000
                }
3001
            }
3002

    
3003
            return _LMSymbol;
3004
        }
3005

    
3006
        /// <summary>
3007
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3008
        /// </summary>
3009
        /// <param name="item"></param>
3010
        /// <param name="connector"></param>
3011
        /// <returns></returns>
3012
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3013
        {
3014
            foreach (var childSymbol in item.ChildSymbols)
3015
            {
3016
                if (childSymbol.Connectors.Contains(connector))
3017
                    return childSymbol;
3018
                else
3019
                    return GetChildSymbolByConnector(childSymbol, connector);
3020
            }
3021

    
3022
            return null;
3023
        }
3024

    
3025
        /// <summary>
3026
        /// EndBreak 모델링 메서드
3027
        /// </summary>
3028
        /// <param name="endBreak"></param>
3029
        private void EndBreakModeling(EndBreak endBreak)
3030
        {
3031
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3032
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3033

    
3034
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3035
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3036
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3037

    
3038
            if (targetLMConnector != null)
3039
            {
3040
                // LEADER Line 검사
3041
                bool leaderLine = false;
3042
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3043
                if (symbolMapping != null)
3044
                    leaderLine = symbolMapping.LEADERLINE;
3045

    
3046
                SegmentLocation location;
3047
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3048
                Array array = null;
3049
                if (point != null)
3050
                    array = new double[] { 0, point[0], point[1] };
3051
                else
3052
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3053
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3054
                if (_LmLabelPersist != null)
3055
                {
3056
                    _LmLabelPersist.Commit();
3057
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3058
                    if (_LmLabelPersist.ModelItemObject != null)
3059
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3060
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3061

    
3062
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3063

    
3064
                    ReleaseCOMObjects(_LmLabelPersist);
3065
                }
3066
                ReleaseCOMObjects(targetLMConnector);
3067
            }
3068
            else
3069
            {
3070
                Log.Write("End Break UID : " + endBreak.UID);
3071
                Log.Write("Can't find targetLMConnector");
3072
            }
3073
        }
3074

    
3075
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3076
        {
3077
            double x = 0, y = 0;
3078
            if (location.HasFlag(SegmentLocation.Up))
3079
                y = GridSetting.GetInstance().Length * 3;
3080
            else if (location.HasFlag(SegmentLocation.Down))
3081
                y = -GridSetting.GetInstance().Length * 3;
3082

    
3083
            if (location.HasFlag(SegmentLocation.Right))
3084
                x = GridSetting.GetInstance().Length * 3;
3085
            else if (location.HasFlag(SegmentLocation.Left))
3086
                x = -GridSetting.GetInstance().Length * 3;
3087

    
3088
            if (x != 0 || y != 0)
3089
            {
3090
                radApp.ActiveSelectSet.RemoveAll();
3091
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3092
                if (dependency != null)
3093
                {
3094
                    radApp.ActiveSelectSet.Add(dependency);
3095
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3096
                    transform.DefineByMove2d(x, y);
3097
                    radApp.ActiveSelectSet.Transform(transform, true);
3098
                    radApp.ActiveSelectSet.RemoveAll();
3099
                }
3100
            }
3101
        }
3102

    
3103
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3104
        {
3105
            string symbolPath = string.Empty;
3106
            #region get symbol path
3107
            if (string.IsNullOrEmpty(changeSymbolPath))
3108
            {
3109
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3110
                symbolPath = GetSPPIDFileName(modelItem);
3111
                ReleaseCOMObjects(modelItem);
3112
            }
3113
            else
3114
                symbolPath = changeSymbolPath;
3115
            
3116
            #endregion
3117

    
3118
            LMConnector newConnector = null;
3119
            dynamic OID = connector.get_GraphicOID().ToString();
3120
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3121
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3122
            int verticesCount = lineStringGeometry.VertexCount;
3123
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3124
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3125

    
3126
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3127
            {
3128
                double[] vertices = null;
3129
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3130
                double x = 0;
3131
                double y = 0;
3132
                lineStringGeometry.GetVertex(1, ref x, ref y);
3133

    
3134
                string flowDirection = string.Empty;
3135
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3136
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3137
                    flowDirection = flowAttribute.get_Value().ToString();
3138

    
3139
                if (flowDirection == "End 1 is downstream (Outlet)")
3140
                {
3141
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3142
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3143
                    flowDirection = "End 1 is upstream (Inlet)";
3144
                }
3145
                else
3146
                {
3147
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3148
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3149
                }
3150
                string oldModelItemId = connector.ModelItemID;
3151
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3152
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3153
                newConnector.Commit();
3154
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3155
                if (!string.IsNullOrEmpty(flowDirection))
3156
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3157
                ReleaseCOMObjects(connector);
3158

    
3159
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3160
                {
3161
                    foreach (var repId in line.SPPID.Representations)
3162
                    {
3163
                        LMConnector _connector = dataSource.GetConnector(repId);
3164
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3165
                        {
3166
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3167
                            {
3168
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3169
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3170
                            }
3171
                        }
3172
                        ReleaseCOMObjects(_connector);
3173
                        _connector = null;
3174
                    }
3175
                }
3176
            }
3177

    
3178
            return newConnector;
3179
        }
3180

    
3181
        /// <summary>
3182
        /// SpecBreak Modeling 메서드
3183
        /// </summary>
3184
        /// <param name="specBreak"></param>
3185
        private void SpecBreakModeling(SpecBreak specBreak)
3186
        {
3187
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3188
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3189

    
3190
            if (upStreamObj != null &&
3191
                downStreamObj != null)
3192
            {
3193
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3194
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3195
                    targetLMConnector != null && 
3196
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3197
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3198

    
3199
                if (targetLMConnector != null)
3200
                {
3201
                    foreach (var attribute in specBreak.ATTRIBUTES)
3202
                    {
3203
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3204
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3205
                        {
3206
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3207
                            SegmentLocation location;
3208
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3209
                            Array array = null;
3210
                            if (point != null)
3211
                                array = new double[] { 0, point[0], point[1] };
3212
                            else
3213
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3214
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3215

    
3216
                            if (_LmLabelPersist != null)
3217
                            {
3218
                                _LmLabelPersist.Commit();
3219
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3220
                                if (_LmLabelPersist.ModelItemObject != null)
3221
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3222
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3223

    
3224
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3225

    
3226
                                ReleaseCOMObjects(_LmLabelPersist);
3227
                            }
3228
                        }
3229
                    }
3230

    
3231
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3232
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3233
                    {
3234
                        // temp
3235
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3236
                    }
3237
                    ReleaseCOMObjects(targetLMConnector);
3238
                }
3239
                else
3240
                {
3241
                    Log.Write("Spec Break UID : " + specBreak.UID);
3242
                    Log.Write("Can't find targetLMConnector");
3243
                }
3244
            }
3245
        }
3246

    
3247
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3248
        {
3249
            LMConnector targetConnector = null;
3250
            Symbol targetSymbol = targetObj as Symbol;
3251
            Symbol connectedSymbol = connectedObj as Symbol;
3252
            Line targetLine = targetObj as Line;
3253
            Line connectedLine = connectedObj as Line;
3254
            if (targetSymbol != null && connectedSymbol != null)
3255
            {
3256
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3257
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3258

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

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

    
3276
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3277
                {
3278
                    if (connector.get_ItemStatus() != "Active")
3279
                        continue;
3280

    
3281
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3282
                    {
3283
                        targetConnector = connector;
3284
                        break;
3285
                    }
3286
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3287
                    {
3288
                        targetConnector = connector;
3289
                        break;
3290
                    }
3291
                }
3292

    
3293
                ReleaseCOMObjects(targetLMSymbol);
3294
                ReleaseCOMObjects(connectedLMSymbol);
3295
            }
3296
            else if (targetLine != null && connectedLine != null)
3297
            {
3298
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3299
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3300

    
3301
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3302
                {
3303
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3304
                    {
3305
                        if (targetConnector != null)
3306
                            break;
3307

    
3308
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3309
                        {
3310
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3311

    
3312
                            if (IsConnected(_LMConnector, connectedModelItem))
3313
                                targetConnector = _LMConnector;
3314
                            else
3315
                                ReleaseCOMObjects(_LMConnector);
3316
                        }
3317
                    }
3318

    
3319
                    ReleaseCOMObjects(targetModelItem);
3320
                }
3321
            }
3322
            else
3323
            {
3324
                LMSymbol connectedLMSymbol = null;
3325
                if (connectedSymbol != null)
3326
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3327
                else if (targetSymbol != null)
3328
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3329
                else
3330
                {
3331

    
3332
                }
3333
                LMModelItem targetModelItem = null;
3334
                if (targetLine != null)
3335
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3336
                else if (connectedLine != null)
3337
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3338
                else
3339
                {
3340

    
3341
                }
3342
                if (connectedLMSymbol != null && targetModelItem != null)
3343
                {
3344
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
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
                    if (targetConnector == null)
3357
                    {
3358
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3359
                        {
3360
                            if (connector.get_ItemStatus() != "Active")
3361
                                continue;
3362

    
3363
                            if (IsConnected(connector, targetModelItem))
3364
                            {
3365
                                targetConnector = connector;
3366
                                break;
3367
                            }
3368
                        }
3369
                    }
3370
                }
3371

    
3372
            }
3373

    
3374
            return targetConnector;
3375
        }
3376

    
3377
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
3378
        {
3379
            double[] result = null;
3380
            Line targetLine = targetObj as Line;
3381
            Symbol targetSymbol = targetObj as Symbol;
3382
            Line connLine = connObj as Line;
3383
            Symbol connSymbol = connObj as Symbol;
3384
            location = SegmentLocation.None;
3385
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3386
            {
3387
                result = GetConnectorVertices(targetConnector)[0];
3388
                if (targetSymbol != null && connSymbol != null)
3389
                {
3390
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3391
                    result = new double[] { result[0], result[1] };
3392
                    if (slopeType == SlopeType.HORIZONTAL)
3393
                        location = SegmentLocation.Up;
3394
                    else if (slopeType == SlopeType.VERTICAL)
3395
                        location = SegmentLocation.Right;
3396
                }
3397
                else if (targetLine != null)
3398
                {
3399
                    result = new double[] { result[0], result[1] };
3400
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3401
                        location = SegmentLocation.Up;
3402
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3403
                        location = SegmentLocation.Right;
3404
                }
3405
                else if (connLine != null)
3406
                {
3407
                    result = new double[] { result[0], result[1] };
3408
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3409
                        location = SegmentLocation.Up;
3410
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3411
                        location = SegmentLocation.Right;
3412
                }
3413
            }
3414
            else
3415
            {
3416
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3417
                {
3418
                    Line line = connObj as Line;
3419
                    LMConnector connectedConnector = null;
3420
                    int connIndex = 0;
3421
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3422
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3423

    
3424
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3425

    
3426
                    ReleaseCOMObjects(modelItem);
3427
                    ReleaseCOMObjects(connectedConnector);
3428

    
3429
                    if (vertices.Count > 0)
3430
                    {
3431
                        if (connIndex == 1)
3432
                            result = vertices[0];
3433
                        else if (connIndex == 2)
3434
                            result = vertices[vertices.Count - 1];
3435

    
3436
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3437
                        {
3438
                            result = new double[] { result[0], result[1] };
3439
                            location = SegmentLocation.Up;
3440
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3441
                                location = location | SegmentLocation.Right;
3442
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3443
                                location = location | SegmentLocation.Left;
3444
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3445
                                location = location | SegmentLocation.Left;
3446
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3447
                                location = location | SegmentLocation.Right;
3448
                        }
3449
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3450
                        {
3451
                            result = new double[] { result[0], result[1] };
3452
                            location = SegmentLocation.Right;
3453
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3454
                                location = location | SegmentLocation.Up;
3455
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3456
                                location = location | SegmentLocation.Down;
3457
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3458
                                location = location | SegmentLocation.Down;
3459
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3460
                                location = location | SegmentLocation.Up;
3461
                        }
3462
                            
3463
                    }
3464
                }
3465
                else
3466
                {
3467
                    Log.Write("error in GetSegemtPoint");
3468
                }
3469
            }
3470

    
3471
            return result;
3472
        }
3473

    
3474
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3475
        {
3476
            bool result = false;
3477

    
3478
            foreach (LMRepresentation rep in modelItem.Representations)
3479
            {
3480
                if (result)
3481
                    break;
3482

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

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

    
3520
                    ReleaseCOMObjects(_LMConnector);
3521
                }
3522
            }
3523

    
3524

    
3525
            return result;
3526
        }
3527

    
3528
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3529
        {
3530
            foreach (LMRepresentation rep in modelItem.Representations)
3531
            {
3532
                if (connectedConnector != null)
3533
                    break;
3534

    
3535
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3536
                {
3537
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3538

    
3539
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3540
                        connector.ConnectItem1SymbolObject != null &&
3541
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3542
                    {
3543
                        connectedConnector = _LMConnector;
3544
                        connectorIndex = 1;
3545
                        break;
3546
                    }
3547
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3548
                        connector.ConnectItem2SymbolObject != null &&
3549
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3550
                    {
3551
                        connectedConnector = _LMConnector;
3552
                        connectorIndex = 2;
3553
                        break;
3554
                    }
3555
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3556
                        connector.ConnectItem1SymbolObject != null &&
3557
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3558
                    {
3559
                        connectedConnector = _LMConnector;
3560
                        connectorIndex = 1;
3561
                        break;
3562
                    }
3563
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3564
                        connector.ConnectItem2SymbolObject != null &&
3565
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3566
                    {
3567
                        connectedConnector = _LMConnector;
3568
                        connectorIndex = 2;
3569
                        break;
3570
                    }
3571

    
3572
                    if (connectedConnector == null)
3573
                        ReleaseCOMObjects(_LMConnector);
3574
                }
3575
            }
3576
        }
3577

    
3578
        /// <summary>
3579
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3580
        /// </summary>
3581
        /// <param name="modelItemID1"></param>
3582
        /// <param name="modelItemID2"></param>
3583
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3584
        {
3585
            try
3586
            {
3587
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3588
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3589
                List<double[]> vertices1 = null;
3590
                string graphicOID1 = string.Empty;
3591
                if (connector1 != null)
3592
                {
3593
                    vertices1 = GetConnectorVertices(connector1);
3594
                    graphicOID1 = connector1.get_GraphicOID();
3595
                }
3596
                _LMAItem item1 = modelItem1.AsLMAItem();
3597
                ReleaseCOMObjects(connector1);
3598
                connector1 = null;
3599

    
3600
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3601
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3602
                List<double[]> vertices2 = null;
3603
                string graphicOID2 = string.Empty;
3604
                if (connector2 != null)
3605
                {
3606
                    vertices2 = GetConnectorVertices(connector2);
3607
                    graphicOID2 = connector2.get_GraphicOID();
3608
                }
3609
                _LMAItem item2 = modelItem2.AsLMAItem();
3610
                ReleaseCOMObjects(connector2);
3611
                connector2 = null;
3612

    
3613
                // item2가 item1으로 조인
3614
                _placement.PIDJoinRuns(ref item1, ref item2);
3615
                item1.Commit();
3616
                item2.Commit();
3617

    
3618
                string beforeID = string.Empty;
3619
                string afterID = string.Empty;
3620

    
3621
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3622
                {
3623
                    beforeID = modelItem2.Id;
3624
                    afterID = modelItem1.Id;
3625
                    survivorId = afterID;
3626
                }
3627
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3628
                {
3629
                    beforeID = modelItem1.Id;
3630
                    afterID = modelItem2.Id;
3631
                    survivorId = afterID;
3632
                }
3633
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3634
                {
3635
                    int model1Cnt = GetConnectorCount(modelId1);
3636
                    int model2Cnt = GetConnectorCount(modelId2);
3637
                    if (model1Cnt == 0)
3638
                    {
3639
                        beforeID = modelItem1.Id;
3640
                        afterID = modelItem2.Id;
3641
                        survivorId = afterID;
3642
                    }
3643
                    else if (model2Cnt == 0)
3644
                    {
3645
                        beforeID = modelItem2.Id;
3646
                        afterID = modelItem1.Id;
3647
                        survivorId = afterID;
3648
                    }
3649
                    else
3650
                        survivorId = null;
3651
                }
3652
                else
3653
                {
3654
                    Log.Write("잘못된 경우");
3655
                    survivorId = null;
3656
                }
3657

    
3658
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3659
                {
3660
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3661
                    foreach (var line in lines)
3662
                        line.SPPID.ModelItemId = afterID;
3663
                }
3664

    
3665
                ReleaseCOMObjects(modelItem1);
3666
                ReleaseCOMObjects(item1);
3667
                ReleaseCOMObjects(modelItem2);
3668
                ReleaseCOMObjects(item2);
3669
            }
3670
            catch (Exception ex)
3671
            {
3672
                Log.Write("Join Error");
3673
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3674
            }
3675
        }
3676

    
3677
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3678
        {
3679
            bool result = false;
3680
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3681
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3682
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3683

    
3684
            foreach (var item in endBreaks)
3685
            {
3686
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3687
                {
3688
                    result = true;
3689
                    break;
3690
                }
3691
            }
3692

    
3693
            return result;
3694
        }
3695
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3696
        {
3697
            List<string> temp = new List<string>();
3698
            List<LMConnector> connectors = new List<LMConnector>();
3699
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3700
            {
3701
                if (connector.get_ItemStatus() != "Active")
3702
                    continue;
3703

    
3704
                LMModelItem modelItem = connector.ModelItemObject;
3705
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3706
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3707
                    temp.Add(modelItem.Id);
3708

    
3709
                if (temp.Contains(modelItem.Id) &&
3710
                    connOtherSymbol != null &&
3711
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3712
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3713
                    temp.Remove(modelItem.Id);
3714

    
3715

    
3716
                if (temp.Contains(modelItem.Id))
3717
                    connectors.Add(connector);
3718
                ReleaseCOMObjects(connOtherSymbol);
3719
                connOtherSymbol = null;
3720
                ReleaseCOMObjects(modelItem);
3721
                modelItem = null;
3722
            }
3723

    
3724
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3725
            {
3726
                if (connector.get_ItemStatus() != "Active")
3727
                    continue;
3728

    
3729
                LMModelItem modelItem = connector.ModelItemObject;
3730
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3731
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3732
                    temp.Add(modelItem.Id);
3733

    
3734
                if (temp.Contains(modelItem.Id) &&
3735
                    connOtherSymbol != null &&
3736
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3737
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3738
                    temp.Remove(modelItem.Id);
3739

    
3740
                if (temp.Contains(modelItem.Id))
3741
                    connectors.Add(connector);
3742
                ReleaseCOMObjects(connOtherSymbol);
3743
                connOtherSymbol = null;
3744
                ReleaseCOMObjects(modelItem);
3745
                modelItem = null;
3746
            }
3747

    
3748

    
3749
            List<string> result = new List<string>();
3750
            string originalName = GetSPPIDFileName(modelId);
3751
            foreach (var connector in connectors)
3752
            {
3753
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3754
                if (originalName == fileName)
3755
                    result.Add(connector.ModelItemID);
3756
                else
3757
                {
3758
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3759
                        result.Add(connector.ModelItemID);
3760
                    else
3761
                    {
3762
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3763
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3764
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3765
                            result.Add(connector.ModelItemID);
3766
                    }
3767
                }
3768
            }
3769

    
3770
            foreach (var connector in connectors)
3771
                ReleaseCOMObjects(connector);
3772
            
3773
            return result;
3774

    
3775

    
3776
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3777
            {
3778
                LMSymbol findResult = null;
3779
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3780
                    findResult = connector.ConnectItem1SymbolObject;
3781
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3782
                    findResult = connector.ConnectItem2SymbolObject;
3783

    
3784
                return findResult;
3785
            }
3786
        }
3787

    
3788
        /// <summary>
3789
        /// PipeRun의 좌표를 가져오는 메서드
3790
        /// </summary>
3791
        /// <param name="modelId"></param>
3792
        /// <returns></returns>
3793
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3794
        {
3795
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3796
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3797

    
3798
            if (modelItem != null)
3799
            {
3800
                foreach (LMRepresentation rep in modelItem.Representations)
3801
                {
3802
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3803
                    {
3804
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3805
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3806
                        {
3807
                            ReleaseCOMObjects(_LMConnector);
3808
                            _LMConnector = null;
3809
                            continue;
3810
                        }
3811
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3812
                        dynamic OID = rep.get_GraphicOID().ToString();
3813
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3814
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3815
                        int verticesCount = lineStringGeometry.VertexCount;
3816
                        double[] vertices = null;
3817
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3818
                        for (int i = 0; i < verticesCount; i++)
3819
                        {
3820
                            double x = 0;
3821
                            double y = 0;
3822
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3823
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3824
                        }
3825
                    }
3826
                }
3827

    
3828
                ReleaseCOMObjects(modelItem);
3829
            }
3830

    
3831
            return connectorVertices;
3832
        }
3833

    
3834
        private List<double[]> GetConnectorVertices(LMConnector connector)
3835
        {
3836
            List<double[]> vertices = new List<double[]>();
3837
            if (connector != null)
3838
            {
3839
                dynamic OID = connector.get_GraphicOID().ToString();
3840
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3841
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3842
                int verticesCount = lineStringGeometry.VertexCount;
3843
                double[] value = null;
3844
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3845
                for (int i = 0; i < verticesCount; i++)
3846
                {
3847
                    double x = 0;
3848
                    double y = 0;
3849
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3850
                    vertices.Add(new double[] { x, y });
3851
                }
3852
            }
3853
            return vertices;
3854
        }
3855

    
3856
        private double GetConnectorDistance(LMConnector connector)
3857
        {
3858
            double result = 0;
3859
            List<double[]> vertices = new List<double[]>();
3860
            if (connector != null)
3861
            {
3862
                dynamic OID = connector.get_GraphicOID().ToString();
3863
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3864
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3865
                int verticesCount = lineStringGeometry.VertexCount;
3866
                double[] value = null;
3867
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3868
                for (int i = 0; i < verticesCount; i++)
3869
                {
3870
                    double x = 0;
3871
                    double y = 0;
3872
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3873
                    vertices.Add(new double[] { x, y });
3874
                    if (vertices.Count > 1)
3875
                    {
3876
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3877
                    }
3878
                }
3879
            }
3880
            return result;
3881
        }
3882
        private double[] GetConnectorRange(LMConnector connector)
3883
        {
3884
            double[] result = null;
3885
            List<double[]> vertices = new List<double[]>();
3886
            if (connector != null)
3887
            {
3888
                dynamic OID = connector.get_GraphicOID().ToString();
3889
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3890
                double minX = 0;
3891
                double minY = 0;
3892
                double maxX = 0;
3893
                double maxY = 0;
3894

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

    
3944
                    if ((x1 <= connX && x2 >= connX) ||
3945
                        (y1 <= connY && y2 >= connY))
3946
                    {
3947
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3948
                        if (length >= distance)
3949
                        {
3950
                            targetConnector = item.Key;
3951
                            length = distance;
3952
                        }
3953

    
3954
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3955
                        if (length >= distance)
3956
                        {
3957
                            targetConnector = item.Key;
3958
                            length = distance;
3959
                        }
3960
                    }
3961
                }
3962
            }
3963

    
3964
            // 못찾았을때.
3965
            length = double.MaxValue;
3966
            if (targetConnector == null)
3967
            {
3968
                foreach (var item in connectorVertices)
3969
                {
3970
                    List<double[]> points = item.Value;
3971

    
3972
                    foreach (double[] point in points)
3973
                    {
3974
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3975
                        if (length >= distance)
3976
                        {
3977
                            targetConnector = item.Key;
3978
                            length = distance;
3979
                        }
3980
                    }
3981
                }
3982
            }
3983

    
3984
            return targetConnector;
3985
        }
3986

    
3987
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3988
        {
3989
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3990
            if (vertices.Count == 0)
3991
                return null;
3992

    
3993
            double length = double.MaxValue;
3994
            LMConnector targetConnector = null;
3995
            double[] resultPoint = null;
3996
            List<double[]> targetVertices = null;
3997

    
3998
            // Vertices 포인트에 제일 가까운곳
3999
            foreach (var item in vertices)
4000
            {
4001
                List<double[]> points = item.Value;
4002
                for (int i = 0; i < points.Count; i++)
4003
                {
4004
                    double[] point = points[i];
4005
                    double tempX = point[0];
4006
                    double tempY = point[1];
4007

    
4008
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4009
                    if (length >= distance)
4010
                    {
4011
                        targetConnector = item.Key;
4012
                        length = distance;
4013
                        resultPoint = point;
4014
                        targetVertices = item.Value;
4015
                    }
4016
                }
4017
            }
4018

    
4019
            // Vertices Cross에 제일 가까운곳
4020
            foreach (var item in vertices)
4021
            {
4022
                List<double[]> points = item.Value;
4023
                for (int i = 0; i < points.Count - 1; i++)
4024
                {
4025
                    double[] point1 = points[i];
4026
                    double[] point2 = points[i + 1];
4027

    
4028
                    double maxLineX = Math.Max(point1[0], point2[0]);
4029
                    double minLineX = Math.Min(point1[0], point2[0]);
4030
                    double maxLineY = Math.Max(point1[1], point2[1]);
4031
                    double minLineY = Math.Min(point1[1], point2[1]);
4032

    
4033
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4034

    
4035
                    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]);
4036
                    if (crossingPoint != null)
4037
                    {
4038
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4039
                        if (length >= distance)
4040
                        {
4041
                            if (slope == SlopeType.Slope &&
4042
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4043
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4044
                            {
4045
                                targetConnector = item.Key;
4046
                                length = distance;
4047
                                resultPoint = crossingPoint;
4048
                                targetVertices = item.Value;
4049
                            }
4050
                            else if (slope == SlopeType.HORIZONTAL &&
4051
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4052
                            {
4053
                                targetConnector = item.Key;
4054
                                length = distance;
4055
                                resultPoint = crossingPoint;
4056
                                targetVertices = item.Value;
4057
                            }
4058
                            else if (slope == SlopeType.VERTICAL &&
4059
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4060
                            {
4061
                                targetConnector = item.Key;
4062
                                length = distance;
4063
                                resultPoint = crossingPoint;
4064
                                targetVertices = item.Value;
4065
                            }
4066
                        }
4067
                    }
4068
                }
4069
            }
4070

    
4071
            foreach (var item in vertices)
4072
                if (item.Key != null && item.Key != targetConnector)
4073
                    ReleaseCOMObjects(item.Key);
4074

    
4075
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4076
            {
4077
                double tempResultX = resultPoint[0];
4078
                double tempResultY = resultPoint[1];
4079
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4080

    
4081
                GridSetting gridSetting = GridSetting.GetInstance();
4082

    
4083
                for (int i = 0; i < targetVertices.Count; i++)
4084
                {
4085
                    double[] point = targetVertices[i];
4086
                    double tempX = targetVertices[i][0];
4087
                    double tempY = targetVertices[i][1];
4088
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4089
                    if (tempX == tempResultX && tempY == tempResultY)
4090
                    {
4091
                        if (i == 0)
4092
                        {
4093
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4094
                            bool containZeroLength = false;
4095
                            if (connSymbol != null)
4096
                            {
4097
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4098
                                {
4099
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4100
                                        containZeroLength = true;
4101
                                }
4102
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4103
                                {
4104
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4105
                                        containZeroLength = true;
4106
                                }
4107
                            }
4108

    
4109
                            if (connSymbol == null ||
4110
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4111
                                containZeroLength)
4112
                            {
4113
                                bool bCalcX = false;
4114
                                bool bCalcY = false;
4115
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4116
                                    bCalcX = true;
4117
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4118
                                    bCalcY = true;
4119
                                else
4120
                                {
4121
                                    bCalcX = true;
4122
                                    bCalcY = true;
4123
                                }
4124

    
4125
                                if (bCalcX)
4126
                                {
4127
                                    double nextX = targetVertices[i + 1][0];
4128
                                    double newX = 0;
4129
                                    if (nextX > tempX)
4130
                                    {
4131
                                        newX = tempX + gridSetting.Length;
4132
                                        if (newX > nextX)
4133
                                            newX = (point[0] + nextX) / 2;
4134
                                    }
4135
                                    else
4136
                                    {
4137
                                        newX = tempX - gridSetting.Length;
4138
                                        if (newX < nextX)
4139
                                            newX = (point[0] + nextX) / 2;
4140
                                    }
4141
                                    resultPoint = new double[] { newX, resultPoint[1] };
4142
                                }
4143

    
4144
                                if (bCalcY)
4145
                                {
4146
                                    double nextY = targetVertices[i + 1][1];
4147
                                    double newY = 0;
4148
                                    if (nextY > tempY)
4149
                                    {
4150
                                        newY = tempY + gridSetting.Length;
4151
                                        if (newY > nextY)
4152
                                            newY = (point[1] + nextY) / 2;
4153
                                    }
4154
                                    else
4155
                                    {
4156
                                        newY = tempY - gridSetting.Length;
4157
                                        if (newY < nextY)
4158
                                            newY = (point[1] + nextY) / 2;
4159
                                    }
4160
                                    resultPoint = new double[] { resultPoint[0], newY };
4161
                                }
4162
                            }
4163
                        }
4164
                        else if (i == targetVertices.Count - 1)
4165
                        {
4166
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4167
                            bool containZeroLength = false;
4168
                            if (connSymbol != null)
4169
                            {
4170
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4171
                                {
4172
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4173
                                        containZeroLength = true;
4174
                                }
4175
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4176
                                {
4177
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4178
                                        containZeroLength = true;
4179
                                }
4180
                            }
4181

    
4182
                            if (connSymbol == null ||
4183
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4184
                                containZeroLength)
4185
                            {
4186
                                bool bCalcX = false;
4187
                                bool bCalcY = false;
4188
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4189
                                    bCalcX = true;
4190
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4191
                                    bCalcY = true;
4192
                                else
4193
                                {
4194
                                    bCalcX = true;
4195
                                    bCalcY = true;
4196
                                }
4197

    
4198
                                if (bCalcX)
4199
                                {
4200
                                    double nextX = targetVertices[i - 1][0];
4201
                                    double newX = 0;
4202
                                    if (nextX > tempX)
4203
                                    {
4204
                                        newX = tempX + gridSetting.Length;
4205
                                        if (newX > nextX)
4206
                                            newX = (point[0] + nextX) / 2;
4207
                                    }
4208
                                    else
4209
                                    {
4210
                                        newX = tempX - gridSetting.Length;
4211
                                        if (newX < nextX)
4212
                                            newX = (point[0] + nextX) / 2;
4213
                                    }
4214
                                    resultPoint = new double[] { newX, resultPoint[1] };
4215
                                }
4216

    
4217
                                if (bCalcY)
4218
                                {
4219
                                    double nextY = targetVertices[i - 1][1];
4220
                                    double newY = 0;
4221
                                    if (nextY > tempY)
4222
                                    {
4223
                                        newY = tempY + gridSetting.Length;
4224
                                        if (newY > nextY)
4225
                                            newY = (point[1] + nextY) / 2;
4226
                                    }
4227
                                    else
4228
                                    {
4229
                                        newY = tempY - gridSetting.Length;
4230
                                        if (newY < nextY)
4231
                                            newY = (point[1] + nextY) / 2;
4232
                                    }
4233
                                    resultPoint = new double[] { resultPoint[0], newY };
4234
                                }
4235
                            }
4236
                        }
4237
                        break;
4238
                    }
4239
                }
4240
            }
4241

    
4242
            x = resultPoint[0];
4243
            y = resultPoint[1];
4244

    
4245
            return targetConnector;
4246
        }
4247

    
4248
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4249
        {
4250
            LMConnector result = null;
4251
            List<LMConnector> connectors = new List<LMConnector>();
4252
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4253

    
4254
            if (modelItem != null)
4255
            {
4256
                foreach (LMRepresentation rep in modelItem.Representations)
4257
                {
4258
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4259
                        connectors.Add(dataSource.GetConnector(rep.Id));
4260
                }
4261

    
4262
                ReleaseCOMObjects(modelItem);
4263
            }
4264

    
4265
            if (connectors.Count == 1)
4266
                result = connectors[0];
4267
            else
4268
                foreach (var item in connectors)
4269
                    ReleaseCOMObjects(item);
4270

    
4271
            return result;
4272
        }
4273

    
4274
        private LMConnector GetLMConnectorFirst(string modelItemID)
4275
        {
4276
            LMConnector result = null;
4277
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4278

    
4279
            if (modelItem != null)
4280
            {
4281
                foreach (LMRepresentation rep in modelItem.Representations)
4282
                {
4283
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4284
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4285
                    {
4286
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4287
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4288
                        {
4289
                            result = connector;
4290
                            break;
4291
                        }
4292
                        else
4293
                        {
4294
                            ReleaseCOMObjects(connector);
4295
                            connector = null;
4296
                        }
4297
                    }
4298
                }
4299
                ReleaseCOMObjects(modelItem);
4300
                modelItem = null;
4301
            }
4302

    
4303
            return result;
4304
        }
4305

    
4306
        private int GetConnectorCount(string modelItemID)
4307
        {
4308
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4309
            int result = 0;
4310
            if (modelItem != null)
4311
            {
4312
                foreach (LMRepresentation rep in modelItem.Representations)
4313
                {
4314
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4315
                        result++;
4316
                    ReleaseCOMObjects(rep);
4317
                }
4318
                ReleaseCOMObjects(modelItem);
4319
            }
4320

    
4321
            return result;
4322
        }
4323

    
4324
        public List<string> GetRepresentations(string modelItemID)
4325
        {
4326
            List<string> result = new List<string>(); ;
4327
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4328
            if (modelItem != null)
4329
            {
4330
                foreach (LMRepresentation rep in modelItem.Representations)
4331
                {
4332
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4333
                        result.Add(rep.Id);
4334
                }
4335
                ReleaseCOMObjects(modelItem);
4336
            }
4337

    
4338
            return result;
4339
        }
4340

    
4341
        private void LineNumberModeling(LineNumber lineNumber)
4342
        {
4343
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4344
            if (line != null)
4345
            {
4346
                double x = 0;
4347
                double y = 0;
4348
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4349

    
4350
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4351
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4352
                if (connectedLMConnector != null)
4353
                {
4354
                    Array points = new double[] { 0, x, y };
4355
                    lineNumber.SPPID.SPPID_X = x;
4356
                    lineNumber.SPPID.SPPID_Y = y;
4357
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4358

    
4359
                    if (_LmLabelPresist != null)
4360
                    {
4361
                        _LmLabelPresist.Commit();
4362
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4363
                        ReleaseCOMObjects(_LmLabelPresist);
4364
                    }
4365
                }
4366

    
4367
                foreach (var item in connectorVertices)
4368
                    ReleaseCOMObjects(item.Key);
4369
            }
4370
        }
4371
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4372
        {
4373
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4374
            if (line == null || line.SPPID.Vertices == null)
4375
                return;
4376

    
4377
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4378
            {
4379
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4380
                if (removeLabel != null)
4381
                {
4382
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4383
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4384

    
4385
                    GridSetting gridSetting = GridSetting.GetInstance();
4386
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4387

    
4388
                    double[] labelRange = null;
4389
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4390
                    List<double[]> vertices = GetConnectorVertices(connector);
4391

    
4392
                    double[] resultStart = null;
4393
                    double[] resultEnd = null;
4394
                    double distance = double.MaxValue;
4395
                    for (int i = 0; i < vertices.Count - 1; i++)
4396
                    {
4397
                        double[] startPoint = vertices[i];
4398
                        double[] endPoint = vertices[i + 1];
4399
                        foreach (var item in line.SPPID.Vertices)
4400
                        {
4401
                            double[] lineStartPoint = item[0];
4402
                            double[] lineEndPoint = item[item.Count - 1];
4403

    
4404
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4405
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4406
                            if (tempDistance < distance)
4407
                            {
4408
                                distance = tempDistance;
4409
                                resultStart = startPoint;
4410
                                resultEnd = endPoint;
4411
                            }
4412
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4413
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4414
                            if (tempDistance < distance)
4415
                            {
4416
                                distance = tempDistance;
4417
                                resultStart = startPoint;
4418
                                resultEnd = endPoint;
4419
                            }
4420
                        }
4421
                    }
4422

    
4423
                    if (resultStart != null && resultEnd != null)
4424
                    {
4425
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4426
                        double lineStartX = 0;
4427
                        double lineStartY = 0;
4428
                        double lineEndX = 0;
4429
                        double lineEndY = 0;
4430
                        double lineNumberX = 0;
4431
                        double lineNumberY = 0;
4432
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4433
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4434

    
4435
                        double lineX = (lineStartX + lineEndX) / 2;
4436
                        double lineY = (lineStartY + lineEndY) / 2;
4437
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4438
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4439

    
4440
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4441
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4442
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4443
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4444

    
4445
                        double offsetX = 0;
4446
                        double offsetY = 0;
4447
                        if (slope == SlopeType.HORIZONTAL)
4448
                        {
4449
                            // Line Number 아래
4450
                            if (lineY < lineNumberY)
4451
                            {
4452
                                offsetX = labelCenterX - SPPIDCenterX;
4453
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4454
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4455
                            }
4456
                            // Line Number 위
4457
                            else
4458
                            {
4459
                                offsetX = labelCenterX - SPPIDCenterX;
4460
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4461
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4462
                            }
4463
                        }
4464
                        else if (slope == SlopeType.VERTICAL)
4465
                        {
4466
                            // Line Number 오르쪽
4467
                            if (lineX < lineNumberX)
4468
                            {
4469
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4470
                                offsetY = labelCenterY - SPPIDCenterY;
4471
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4472
                            }
4473
                            // Line Number 왼쪽
4474
                            else
4475
                            {
4476
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4477
                                offsetY = labelCenterY - SPPIDCenterY;
4478
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4479
                            }
4480
                        }
4481

    
4482
                        if (offsetY != 0 || offsetY != 0)
4483
                        {
4484
                            if (connector.ConnectItem1SymbolObject != null &&
4485
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4486
                            {
4487
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4488

    
4489
                                double x1, y1, x2, y2, originX, originY;
4490
                                symbol.Range(out x1, out y1, out x2, out y2);
4491
                                symbol.GetOrigin(out originX, out originY);
4492
                                if (originX < lineNumber.SPPID.SPPID_X)
4493
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4494
                                else
4495
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4496
                            }
4497
                            else if (connector.ConnectItem2SymbolObject != null &&
4498
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4499
                            {
4500
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4501

    
4502
                                double x1, y1, x2, y2, originX, originY;
4503
                                symbol.Range(out x1, out y1, out x2, out y2);
4504
                                symbol.GetOrigin(out originX, out originY);
4505
                                if (originX < lineNumber.SPPID.SPPID_X)
4506
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4507
                                else
4508
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4509
                            }
4510

    
4511
                            radApp.ActiveSelectSet.RemoveAll();
4512
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
4513
                            if (dependency != null)
4514
                            {
4515
                                radApp.ActiveSelectSet.Add(dependency);
4516
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4517
                                transform.DefineByMove2d(-offsetX, -offsetY);
4518
                                radApp.ActiveSelectSet.Transform(transform, true);
4519
                                radApp.ActiveSelectSet.RemoveAll();
4520
                            }
4521
                        }
4522

    
4523
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4524
                        {
4525
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4526
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4527
                        }
4528
                    }
4529

    
4530

    
4531
                    ReleaseCOMObjects(connector);
4532
                    connector = null;
4533
                }
4534

    
4535
                ReleaseCOMObjects(removeLabel);
4536
                removeLabel = null;
4537
            }
4538
        }
4539
        /// <summary>
4540
        /// Flow Mark Modeling
4541
        /// </summary>
4542
        /// <param name="line"></param>
4543
        private void FlowMarkModeling(Line line)
4544
        {
4545
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4546
            {
4547
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4548
                if (connector != null)
4549
                {
4550
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4551
                    List<double[]> vertices = GetConnectorVertices(connector);
4552
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4553
                    double[] point = vertices[vertices.Count - 1];
4554
                    Array array = new double[] { 0, point[0], point[1] };
4555
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4556
                    if (_LMLabelPersist != null)
4557
                    {
4558
                        _LMLabelPersist.Commit();
4559
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4560
                        ReleaseCOMObjects(_LMLabelPersist);
4561
                    }
4562
                }
4563
            }
4564
        }
4565

    
4566
        /// <summary>
4567
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4568
        /// </summary>
4569
        /// <param name="lineNumber"></param>
4570
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4571
        {
4572
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4573
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4574
            {
4575
                if (a.ATTRIBUTE == "Tag Seq No")
4576
                    return 1;
4577
                else if (b.ATTRIBUTE == "Tag Seq No")
4578
                    return -1;
4579

    
4580
                return 0;
4581
            }
4582

    
4583
            foreach (LineRun run in lineNumber.RUNS)
4584
            {
4585
                foreach (var item in run.RUNITEMS)
4586
                {
4587
                    if (item.GetType() == typeof(Symbol))
4588
                    {
4589
                        Symbol symbol = item as Symbol;
4590
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4591
                        if (_LMSymbol != null)
4592
                        {
4593
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4594

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

    
4648
                                                    if (_LMAAttribute != null)
4649
                                                    {
4650
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4651
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4652
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4653
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4654
                                                    }
4655
                                                }
4656
                                                if (dt != null)
4657
                                                    dt.Dispose();
4658
                                            }
4659
                                        }
4660
                                        else if (_LMAAttribute != null)
4661
                                        {
4662
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4663
                                                _LMAAttribute.set_Value(attribute.VALUE);
4664
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4665
                                                _LMAAttribute.set_Value(attribute.VALUE);
4666
                                        }
4667
                                    }
4668
                                }
4669
                                _LMModelItem.Commit();
4670
                            }
4671
                            if (_LMModelItem != null)
4672
                                ReleaseCOMObjects(_LMModelItem);
4673
                            endLine.Add(line.SPPID.ModelItemId);
4674
                        }
4675
                    }
4676
                }
4677
            }
4678
        }
4679

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

    
4728
                ReleaseCOMObjects(_Attributes);
4729
                ReleaseCOMObjects(_LMModelItem);
4730
                ReleaseCOMObjects(_LMSymbol);
4731
            }
4732
            else if (!string.IsNullOrEmpty(sModelID))
4733
            {
4734
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
4735
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4736

    
4737
                foreach (var item in targetAttributes)
4738
                {
4739
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4740
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4741
                    {
4742
                        if (!mapping.IsText)
4743
                        {
4744
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4745
                            if (_Attribute != null)
4746
                                _Attribute.set_Value(item.VALUE);
4747
                        }
4748
                    }
4749
                }
4750
                _LMModelItem.Commit();
4751

    
4752
                ReleaseCOMObjects(_Attributes);
4753
                ReleaseCOMObjects(_LMModelItem);
4754
            }
4755
        }
4756

    
4757
        /// <summary>
4758
        /// Input SpecBreak Attribute
4759
        /// </summary>
4760
        /// <param name="specBreak"></param>
4761
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4762
        {
4763
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4764
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4765

    
4766
            if (upStreamObj != null &&
4767
                downStreamObj != null)
4768
            {
4769
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4770

    
4771
                if (targetLMConnector != null)
4772
                {
4773
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4774
                    {
4775
                        string symbolPath = _LMLabelPersist.get_FileName();
4776
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4777
                        if (mapping != null)
4778
                        {
4779
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4780
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4781
                            {
4782
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4783
                                if (values.Length == 2)
4784
                                {
4785
                                    string upStreamValue = values[0];
4786
                                    string downStreamValue = values[1];
4787

    
4788
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4789
                                }
4790
                            }
4791
                        }
4792
                    }
4793

    
4794
                    ReleaseCOMObjects(targetLMConnector);
4795
                }
4796
            }
4797

    
4798

    
4799
            #region 내부에서만 쓰는 메서드
4800
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4801
            {
4802
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4803
                Line upStreamLine = _upStreamObj as Line;
4804
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4805
                Line downStreamLine = _downStreamObj as Line;
4806
                // 둘다 Line일 경우
4807
                if (upStreamLine != null && downStreamLine != null)
4808
                {
4809
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4810
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4811
                }
4812
                // 둘다 Symbol일 경우
4813
                else if (upStreamSymbol != null && downStreamSymbol != null)
4814
                {
4815
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4816
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4817
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4818

    
4819
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4820
                    {
4821
                        if (connector.get_ItemStatus() != "Active")
4822
                            continue;
4823

    
4824
                        if (connector.Id != zeroLenthConnector.Id)
4825
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4826
                    }
4827

    
4828
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4829
                    {
4830
                        if (connector.get_ItemStatus() != "Active")
4831
                            continue;
4832

    
4833
                        if (connector.Id != zeroLenthConnector.Id)
4834
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4835
                    }
4836

    
4837
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4838
                    {
4839
                        if (connector.get_ItemStatus() != "Active")
4840
                            continue;
4841

    
4842
                        if (connector.Id != zeroLenthConnector.Id)
4843
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4844
                    }
4845

    
4846
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4847
                    {
4848
                        if (connector.get_ItemStatus() != "Active")
4849
                            continue;
4850

    
4851
                        if (connector.Id != zeroLenthConnector.Id)
4852
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4853
                    }
4854

    
4855
                    ReleaseCOMObjects(zeroLenthConnector);
4856
                    ReleaseCOMObjects(upStreamLMSymbol);
4857
                    ReleaseCOMObjects(downStreamLMSymbol);
4858
                }
4859
                else if (upStreamSymbol != null && downStreamLine != null)
4860
                {
4861
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4862
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4863
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4864

    
4865
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4866
                    {
4867
                        if (connector.get_ItemStatus() != "Active")
4868
                            continue;
4869

    
4870
                        if (connector.Id == zeroLenthConnector.Id)
4871
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4872
                    }
4873

    
4874
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4875
                    {
4876
                        if (connector.get_ItemStatus() != "Active")
4877
                            continue;
4878

    
4879
                        if (connector.Id == zeroLenthConnector.Id)
4880
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4881
                    }
4882

    
4883
                    ReleaseCOMObjects(zeroLenthConnector);
4884
                    ReleaseCOMObjects(upStreamLMSymbol);
4885
                }
4886
                else if (upStreamLine != null && downStreamSymbol != null)
4887
                {
4888
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4889
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4890
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4891

    
4892
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4893
                    {
4894
                        if (connector.get_ItemStatus() != "Active")
4895
                            continue;
4896

    
4897
                        if (connector.Id == zeroLenthConnector.Id)
4898
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4899
                    }
4900

    
4901
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4902
                    {
4903
                        if (connector.get_ItemStatus() != "Active")
4904
                            continue;
4905

    
4906
                        if (connector.Id == zeroLenthConnector.Id)
4907
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4908
                    }
4909

    
4910
                    ReleaseCOMObjects(zeroLenthConnector);
4911
                    ReleaseCOMObjects(downStreamLMSymbol);
4912
                }
4913
            }
4914

    
4915
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4916
            {
4917
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4918
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4919
                {
4920
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4921
                    if (_LMAAttribute != null)
4922
                    {
4923
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4924
                            _LMAAttribute.set_Value(value);
4925
                        else if (_LMAAttribute.get_Value() != value)
4926
                            _LMAAttribute.set_Value(value);
4927
                    }
4928

    
4929
                    _LMModelItem.Commit();
4930
                }
4931
                if (_LMModelItem != null)
4932
                    ReleaseCOMObjects(_LMModelItem);
4933
            }
4934

    
4935
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4936
            {
4937
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4938
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4939
                {
4940
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4941
                    if (_LMAAttribute != null)
4942
                    {
4943
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4944
                            _LMAAttribute.set_Value(value);
4945
                        else if (_LMAAttribute.get_Value() != value)
4946
                            _LMAAttribute.set_Value(value);
4947
                    }
4948

    
4949
                    _LMModelItem.Commit();
4950
                }
4951
                if (_LMModelItem != null)
4952
                    ReleaseCOMObjects(_LMModelItem);
4953
            }
4954
            #endregion
4955
        }
4956

    
4957
        private void InputEndBreakAttribute(EndBreak endBreak)
4958
        {
4959
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4960
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4961

    
4962
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4963
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4964
            {
4965
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4966
                if (labelPersist != null)
4967
                {
4968
                    LMRepresentation representation = labelPersist.RepresentationObject;
4969
                    if (representation != null)
4970
                    {
4971
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4972
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4973
                        string modelItemID = connector.ModelItemID;
4974
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4975
                        {
4976
                            List<string> modelItemIDs = new List<string>();
4977
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4978
                            {
4979
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4980
                                foreach (LMConnector item in symbol.Connect1Connectors)
4981
                                {
4982
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4983
                                        modelItemIDs.Add(item.ModelItemID);
4984
                                    ReleaseCOMObjects(item);
4985
                                }
4986
                                foreach (LMConnector item in symbol.Connect2Connectors)
4987
                                {
4988
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4989
                                        modelItemIDs.Add(item.ModelItemID);
4990
                                    ReleaseCOMObjects(item);
4991
                                }
4992
                                ReleaseCOMObjects(symbol);
4993
                                symbol = null;
4994
                            }
4995
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4996
                            {
4997
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4998
                                foreach (LMConnector item in symbol.Connect1Connectors)
4999
                                {
5000
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5001
                                        modelItemIDs.Add(item.ModelItemID);
5002
                                    ReleaseCOMObjects(item);
5003
                                }
5004
                                foreach (LMConnector item in symbol.Connect2Connectors)
5005
                                {
5006
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5007
                                        modelItemIDs.Add(item.ModelItemID);
5008
                                    ReleaseCOMObjects(item);
5009
                                }
5010
                                ReleaseCOMObjects(symbol);
5011
                                symbol = null;
5012
                            }
5013

    
5014
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5015
                            if (modelItemIDs.Count == 1)
5016
                            {
5017
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5018
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5019
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5020
                                {
5021
                                    bool result = false;
5022
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5023
                                    {
5024
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5025
                                            result = true;
5026
                                        ReleaseCOMObjects(loop);
5027
                                    }
5028

    
5029
                                    if (result)
5030
                                    {
5031
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5032
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5033
                                        ZeroLengthModelItem.Commit();
5034
                                    }
5035
                                    else
5036
                                    {
5037
                                        List<string> loopModelItems = new List<string>();
5038
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5039
                                        {
5040
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5041
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5042
                                            {
5043
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5044
                                                    loopModelItems.Add(loop.ModelItemID);
5045
                                                ReleaseCOMObjects(loop);
5046
                                            }
5047
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5048
                                            {
5049
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5050
                                                    loopModelItems.Add(loop.ModelItemID);
5051
                                                ReleaseCOMObjects(loop);
5052
                                            }
5053
                                            ReleaseCOMObjects(_symbol);
5054
                                            _symbol = null;
5055
                                        }
5056
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5057
                                        {
5058
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5059
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5060
                                            {
5061
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5062
                                                    loopModelItems.Add(loop.ModelItemID);
5063
                                                ReleaseCOMObjects(loop);
5064
                                            }
5065
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5066
                                            {
5067
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5068
                                                    loopModelItems.Add(loop.ModelItemID);
5069
                                                ReleaseCOMObjects(loop);
5070
                                            }
5071
                                            ReleaseCOMObjects(_symbol);
5072
                                            _symbol = null;
5073
                                        }
5074

    
5075
                                        loopModelItems = loopModelItems.Distinct().ToList();
5076
                                        if (loopModelItems.Count == 1)
5077
                                        {
5078
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5079
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5080
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5081
                                            modelItem.Commit();
5082
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5083
                                            ZeroLengthModelItem.Commit();
5084

    
5085
                                            ReleaseCOMObjects(loopModelItem);
5086
                                            loopModelItem = null;
5087
                                        }
5088
                                    }
5089
                                }
5090
                                else
5091
                                {
5092
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5093
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5094
                                    ZeroLengthModelItem.Commit();
5095
                                }
5096
                                ReleaseCOMObjects(modelItem);
5097
                                modelItem = null;
5098
                                ReleaseCOMObjects(onlyOne);
5099
                                onlyOne = null;
5100
                            }
5101
                        }
5102
                        ReleaseCOMObjects(connector);
5103
                        connector = null;
5104
                        ReleaseCOMObjects(ZeroLengthModelItem);
5105
                        ZeroLengthModelItem = null;
5106
                    }
5107
                    ReleaseCOMObjects(representation);
5108
                    representation = null;
5109
                }
5110
                ReleaseCOMObjects(labelPersist);
5111
                labelPersist = null;
5112
            }
5113
        }
5114

    
5115
        /// <summary>
5116
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5117
        /// </summary>
5118
        /// <param name="text"></param>
5119
        private void NormalTextModeling(Text text)
5120
        {
5121
            LMSymbol _LMSymbol = null;
5122

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

    
5126
            double x = 0;
5127
            double y = 0;
5128
            double angle = text.ANGLE;
5129
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5130

    
5131
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5132
            text.SPPID.SPPID_X = x;
5133
            text.SPPID.SPPID_Y = y;
5134

    
5135
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5136
            if (_LMSymbol != null)
5137
            {
5138
                _LMSymbol.Commit();
5139
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5140
                if (_LMItemNote != null)
5141
                {
5142
                    _LMItemNote.Commit();
5143
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5144
                    if (_LMAAttribute != null)
5145
                    {
5146
                        _LMAAttribute.set_Value(text.VALUE);
5147
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5148
                        _LMItemNote.Commit();
5149

    
5150

    
5151
                        double[] range = null;
5152
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5153
                        {
5154
                            double[] temp = null;
5155
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5156
                            if (temp != null)
5157
                            {
5158
                                if (range == null)
5159
                                    range = temp;
5160
                                else
5161
                                {
5162
                                    range = new double[] {
5163
                                            Math.Min(range[0], temp[0]),
5164
                                            Math.Min(range[1], temp[1]),
5165
                                            Math.Max(range[2], temp[2]),
5166
                                            Math.Max(range[3], temp[3])
5167
                                        };
5168
                                }
5169
                            }
5170
                        }
5171
                        text.SPPID.Range = range;
5172

    
5173
                        if (_LMAAttribute != null)
5174
                            ReleaseCOMObjects(_LMAAttribute);
5175
                        if (_LMItemNote != null)
5176
                            ReleaseCOMObjects(_LMItemNote);
5177
                    }
5178

    
5179
                    TextCorrectModeling(text);
5180
                }
5181
            }
5182
            if (_LMSymbol != null)
5183
                ReleaseCOMObjects(_LMSymbol);
5184
        }
5185

    
5186
        private void DefaultTextModeling(string value, double x, double y)
5187
        {
5188
            LMSymbol _LMSymbol = null;
5189

    
5190
            LMItemNote _LMItemNote = null;
5191
            LMAAttribute _LMAAttribute = null;
5192

    
5193
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5194
            if (_LMSymbol != null)
5195
            {
5196
                _LMSymbol.Commit();
5197
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5198
                if (_LMItemNote != null)
5199
                {
5200
                    _LMItemNote.Commit();
5201
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5202
                    if (_LMAAttribute != null)
5203
                    {
5204
                        _LMAAttribute.set_Value(value);
5205
                        _LMItemNote.Commit();
5206

    
5207
                        if (_LMAAttribute != null)
5208
                            ReleaseCOMObjects(_LMAAttribute);
5209
                        if (_LMItemNote != null)
5210
                            ReleaseCOMObjects(_LMItemNote);
5211
                    }
5212
                }
5213
            }
5214
            if (_LMSymbol != null)
5215
                ReleaseCOMObjects(_LMSymbol);
5216
        }
5217

    
5218
        private void AssociationTextModeling(Text text)
5219
        {
5220
            LMSymbol _LMSymbol = null;
5221
            LMConnector connectedLMConnector = null;
5222
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5223
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
5224
            {
5225
                Symbol symbol = owner as Symbol;
5226
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5227
                if (_LMSymbol != null)
5228
                {
5229
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5230
                    {
5231
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5232
                        {
5233
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5234

    
5235
                            if (mapping != null)
5236
                            {
5237
                                double x = 0;
5238
                                double y = 0;
5239

    
5240
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5241
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5242
                                Array array = new double[] { 0, x, y };
5243
                                text.SPPID.SPPID_X = x;
5244
                                text.SPPID.SPPID_Y = y;
5245
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5246
                                if (_LMLabelPersist != null)
5247
                                {
5248
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5249
                                    _LMLabelPersist.Commit();
5250
                                    ReleaseCOMObjects(_LMLabelPersist);
5251
                                }
5252
                            }
5253
                        }
5254
                    }
5255
                }
5256
            }
5257
            else if (owner != null && owner.GetType() == typeof(Line))
5258
            {
5259
                Line line = owner as Line;
5260
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5261
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5262

    
5263
                if (connectedLMConnector != null)
5264
                {
5265
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5266
                    {
5267
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5268
                        {
5269
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5270

    
5271
                            if (mapping != null)
5272
                            {
5273
                                double x = 0;
5274
                                double y = 0;
5275
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5276
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5277
                                Array array = new double[] { 0, x, y };
5278

    
5279
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5280
                                if (_LMLabelPersist != null)
5281
                                {
5282
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5283
                                    _LMLabelPersist.Commit();
5284

    
5285
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5286
                                    if (dependency != null)
5287
                                    {
5288
                                        radApp.ActiveSelectSet.RemoveAll();
5289
                                        radApp.ActiveSelectSet.Add(dependency);
5290
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
5291
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5292
                                        radApp.ActiveSelectSet.Transform(transform, true);
5293
                                        radApp.ActiveSelectSet.RemoveAll();
5294
                                    }
5295

    
5296
                                    ReleaseCOMObjects(_LMLabelPersist);
5297
                                }
5298
                            }
5299
                        }
5300
                    }
5301
                }
5302
            }
5303
            if (_LMSymbol != null)
5304
                ReleaseCOMObjects(_LMSymbol);
5305
        }
5306

    
5307
        private void TextCorrectModeling(Text text)
5308
        {
5309
            if (text.SPPID.Range == null)
5310
                return;
5311

    
5312
            bool needRemodeling = false;
5313
            bool loop = true;
5314
            GridSetting gridSetting = GridSetting.GetInstance();
5315
            while (loop)
5316
            {
5317
                loop = false;
5318
                foreach (var overlapText in document.TEXTINFOS)
5319
                {
5320
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5321
                        continue;
5322

    
5323
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5324
                    {
5325
                        double percentX = 0;
5326
                        double percentY = 0;
5327
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5328
                        {
5329
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5330
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5331
                        }
5332
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5333
                        {
5334
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5335
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5336
                        }
5337

    
5338
                        double tempX = 0;
5339
                        double tempY = 0;
5340
                        bool overlapX = false;
5341
                        bool overlapY = false;
5342
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5343
                        if (percentX >= percentY)
5344
                        {
5345
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5346
                            double move = gridSetting.Length * count;
5347
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5348
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5349
                            needRemodeling = true;
5350
                            loop = true;
5351
                        }
5352
                        else
5353
                        {
5354
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5355
                            double move = gridSetting.Length * count;
5356
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5357
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5358
                            needRemodeling = true;
5359
                            loop = true;
5360
                        }
5361
                    }
5362
                }
5363
            }
5364
            
5365

    
5366
            if (needRemodeling)
5367
            {
5368
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5369
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5370
                text.SPPID.RepresentationId = null;
5371

    
5372
                LMItemNote _LMItemNote = null;
5373
                LMAAttribute _LMAAttribute = null;
5374
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5375
                if (_LMSymbol != null)
5376
                {
5377
                    _LMSymbol.Commit();
5378
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5379
                    if (_LMItemNote != null)
5380
                    {
5381
                        _LMItemNote.Commit();
5382
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5383
                        if (_LMAAttribute != null)
5384
                        {
5385
                            _LMAAttribute.set_Value(text.VALUE);
5386
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5387
                            _LMItemNote.Commit();
5388

    
5389
                            ReleaseCOMObjects(_LMAAttribute);
5390
                            ReleaseCOMObjects(_LMItemNote);
5391
                        }
5392
                    }
5393
                }
5394

    
5395
                ReleaseCOMObjects(symbol);
5396
                symbol = null;
5397
                ReleaseCOMObjects(_LMItemNote);
5398
                _LMItemNote = null;
5399
                ReleaseCOMObjects(_LMAAttribute);
5400
                _LMAAttribute = null;
5401
                ReleaseCOMObjects(_LMSymbol);
5402
                _LMSymbol = null;
5403
            }
5404
        }
5405

    
5406
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5407
        {
5408
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5409
            {
5410
                List<Text> allTexts = new List<Text>();
5411
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5412
                LMRepresentation representation = targetLabel.RepresentationObject;
5413
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5414
                if (targetLabel.RepresentationObject != null && symbol != null)
5415
                {
5416
                    double[] symbolRange = null;
5417
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5418
                    if (symbolRange != null)
5419
                    {
5420
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5421
                        {
5422
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5423
                            if (findText != null)
5424
                            {
5425
                                double[] range = null;
5426
                                GetSPPIDSymbolRange(labelPersist, ref range);
5427
                                findText.SPPID.Range = range;
5428
                                allTexts.Add(findText);
5429
                            }
5430

    
5431
                            ReleaseCOMObjects(labelPersist);
5432
                        }
5433

    
5434
                        if (allTexts.Count > 0)
5435
                        {
5436
                            #region Sort Text By Y
5437
                            allTexts.Sort(SortTextByY);
5438
                            int SortTextByY(Text a, Text b)
5439
                            {
5440
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5441
                            }
5442
                            #endregion
5443

    
5444
                            #region 정렬하기전 방향
5445
                            List<Text> left = new List<Text>();
5446
                            List<Text> down = new List<Text>();
5447
                            List<Text> right = new List<Text>();
5448
                            List<Text> up = new List<Text>();
5449
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5450
                            foreach (var loopText in allTexts)
5451
                            {
5452
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5453
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5454
                                double originX = 0;
5455
                                double originY = 0;
5456
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5457
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5458

    
5459
                                if (angle < 45)
5460
                                {
5461
                                    // Text 오른쪽
5462
                                    if (textCenterX > originX)
5463
                                        right.Add(loopText);
5464
                                    // Text 왼쪽
5465
                                    else
5466
                                        left.Add(loopText); 
5467
                                }
5468
                                else
5469
                                {
5470
                                    // Text 아래쪽
5471
                                    if (textCenterY > originY)
5472
                                        down.Add(loopText);
5473
                                    // Text 위쪽
5474
                                    else
5475
                                        up.Add(loopText);
5476
                                }
5477
                            }
5478
                            
5479
                            #endregion
5480

    
5481
                            foreach (var texts in sortTexts)
5482
                            {
5483
                                if (texts.Count == 0 )
5484
                                    continue;
5485
                                
5486
                                #region 첫번째 Text로 기준 맞춤
5487
                                for (int i = 0; i < texts.Count; i++)
5488
                                {
5489
                                    if (i != 0)
5490
                                    {
5491
                                        Text currentText = texts[i];
5492
                                        Text prevText = texts[i - 1];
5493
                                        double minY = prevText.SPPID.Range[1];
5494
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5495
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5496
                                        double _gapX = centerX - centerPrevX;
5497
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5498
                                        MoveText(currentText, _gapX, _gapY);
5499
                                    }
5500
                                }
5501
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5502
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5503
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5504
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5505
                                rangeMinX.Sort();
5506
                                rangeMinY.Sort();
5507
                                rangeMaxX.Sort();
5508
                                rangeMaxY.Sort();
5509
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5510
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5511
                                #endregion
5512
                                #region 정렬
5513
                                Text correctBySymbol = texts[0];
5514
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5515
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5516
                                double originX = 0;
5517
                                double originY = 0;
5518
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5519
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5520
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5521
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5522

    
5523
                                double gapX = 0;
5524
                                double gapY = 0;
5525
                                if (angle < 45)
5526
                                {
5527
                                    // Text 오른쪽
5528
                                    if (textCenterX > originX)
5529
                                    {
5530
                                        gapX = rangeMinX[0] - symbolRange[2];
5531
                                        gapY = allTextCenterY - symbolCenterY;
5532
                                    }
5533
                                    // Text 왼쪽
5534
                                    else
5535
                                    {
5536
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5537
                                        gapY = allTextCenterY - symbolCenterY;
5538
                                    }
5539
                                }
5540
                                else
5541
                                {
5542
                                    // Text 아래쪽
5543
                                    if (textCenterY > originY)
5544
                                    {
5545
                                        gapX = allTextCenterX - symbolCenterX;
5546
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5547
                                    }
5548
                                    // Text 위쪽
5549
                                    else
5550
                                    {
5551
                                        gapX = allTextCenterX - symbolCenterX;
5552
                                        gapY = rangeMinY[0] - symbolRange[3];
5553
                                    }
5554
                                }
5555

    
5556
                                foreach (var item in texts)
5557
                                {
5558
                                    MoveText(item, gapX, gapY);
5559
                                    RemodelingAssociationText(item);
5560
                                }
5561
                                #endregion
5562
                            }
5563
                        }
5564
                    }
5565
                }
5566

    
5567
                void MoveText(Text moveText, double x, double y)
5568
                {
5569
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5570
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5571
                    moveText.SPPID.Range = new double[] {
5572
                        moveText.SPPID.Range[0] - x,
5573
                        moveText.SPPID.Range[1]- y,
5574
                        moveText.SPPID.Range[2]- x,
5575
                        moveText.SPPID.Range[3]- y
5576
                    };
5577
                }
5578

    
5579
                endTexts.AddRange(allTexts);
5580

    
5581
                ReleaseCOMObjects(targetLabel);
5582
                targetLabel = null;
5583
                ReleaseCOMObjects(representation);
5584
                representation = null;
5585
            }
5586
        }
5587

    
5588
        private void RemodelingAssociationText(Text text)
5589
        {
5590
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5591
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5592
            removeLabel.Commit();
5593
            ReleaseCOMObjects(removeLabel);
5594
            removeLabel = null;
5595

    
5596
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5597
            if (owner != null && owner.GetType() == typeof(Symbol))
5598
            {
5599
                Symbol symbol = owner as Symbol;
5600
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5601
                if (_LMSymbol != null)
5602
                {
5603
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5604
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5605
                    {
5606
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5607

    
5608
                        if (mapping != null)
5609
                        {
5610
                            double x = 0;
5611
                            double y = 0;
5612

    
5613
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5614
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5615
                            if (_LMLabelPersist != null)
5616
                            {
5617
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5618
                                _LMLabelPersist.Commit();
5619
                            }
5620
                            ReleaseCOMObjects(_LMLabelPersist);
5621
                            _LMLabelPersist = null;
5622
                        }
5623
                    }
5624
                }
5625
                ReleaseCOMObjects(_LMSymbol);
5626
                _LMSymbol = null;
5627
            }
5628
        }
5629

    
5630
        /// <summary>
5631
        /// Note Modeling
5632
        /// </summary>
5633
        /// <param name="note"></param>
5634
        private void NoteModeling(Note note, List<Note> correctList)
5635
        {
5636
            LMSymbol _LMSymbol = null;
5637
            LMItemNote _LMItemNote = null;
5638
            LMAAttribute _LMAAttribute = null;
5639

    
5640
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5641
            {
5642
                double x = 0;
5643
                double y = 0;
5644

    
5645
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5646
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5647
                note.SPPID.SPPID_X = x;
5648
                note.SPPID.SPPID_Y = y;
5649

    
5650
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5651
                if (_LMSymbol != null)
5652
                {
5653
                    _LMSymbol.Commit();
5654
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5655
                    if (_LMItemNote != null)
5656
                    {
5657
                        _LMItemNote.Commit();
5658
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5659
                        if (_LMAAttribute != null)
5660
                        {
5661
                            _LMAAttribute.set_Value(note.VALUE);
5662
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5663

    
5664
                            double[] range = null;
5665
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5666
                            {
5667
                                double[] temp = null;
5668
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5669
                                if (temp != null)
5670
                                {
5671
                                    if (range == null)
5672
                                        range = temp;
5673
                                    else
5674
                                    {
5675
                                        range = new double[] {
5676
                                            Math.Min(range[0], temp[0]),
5677
                                            Math.Min(range[1], temp[1]),
5678
                                            Math.Max(range[2], temp[2]),
5679
                                            Math.Max(range[3], temp[3])
5680
                                        };
5681
                                    }
5682
                                }
5683
                            }
5684
                            if (range != null)
5685
                                correctList.Add(note);
5686
                            note.SPPID.Range = range;
5687

    
5688

    
5689
                            _LMItemNote.Commit();
5690
                        }
5691
                    }
5692
                }
5693
            }
5694

    
5695
            if (_LMAAttribute != null)
5696
                ReleaseCOMObjects(_LMAAttribute);
5697
            if (_LMItemNote != null)
5698
                ReleaseCOMObjects(_LMItemNote);
5699
            if (_LMSymbol != null)
5700
                ReleaseCOMObjects(_LMSymbol);
5701
        }
5702

    
5703
        private void NoteCorrectModeling(Note note, List<Note> endList)
5704
        {
5705
            bool needRemodeling = false;
5706
            bool loop = true;
5707
            GridSetting gridSetting = GridSetting.GetInstance();
5708
            while (loop)
5709
            {
5710
                loop = false;
5711
                foreach (var overlap in endList)
5712
                {
5713
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5714
                    {
5715
                        double tempX = 0;
5716
                        double tempY = 0;
5717
                        bool overlapX = false;
5718
                        bool overlapY = false;
5719
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5720
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5721
                        if (overlapY && angle >= 45)
5722
                        {
5723
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5724
                            double move = gridSetting.Length * count;
5725
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5726
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5727
                            needRemodeling = true;
5728
                            loop = true;
5729
                        }
5730
                        if (overlapX && angle <= 45)
5731
                        {
5732
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5733
                            double move = gridSetting.Length * count;
5734
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5735
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5736
                            needRemodeling = true;
5737
                            loop = true;
5738
                        }
5739
                    }
5740
                }
5741
            }
5742

    
5743

    
5744
            if (needRemodeling)
5745
            {
5746
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5747
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5748
                note.SPPID.RepresentationId = null;
5749

    
5750
                LMItemNote _LMItemNote = null;
5751
                LMAAttribute _LMAAttribute = null;
5752
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5753
                if (_LMSymbol != null)
5754
                {
5755
                    _LMSymbol.Commit();
5756
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5757
                    if (_LMItemNote != null)
5758
                    {
5759
                        _LMItemNote.Commit();
5760
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5761
                        if (_LMAAttribute != null)
5762
                        {
5763
                            _LMAAttribute.set_Value(note.VALUE);
5764
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5765
                            _LMItemNote.Commit();
5766

    
5767
                            ReleaseCOMObjects(_LMAAttribute);
5768
                            ReleaseCOMObjects(_LMItemNote);
5769
                        }
5770
                    }
5771
                }
5772

    
5773
                ReleaseCOMObjects(symbol);
5774
                symbol = null;
5775
                ReleaseCOMObjects(_LMItemNote);
5776
                _LMItemNote = null;
5777
                ReleaseCOMObjects(_LMAAttribute);
5778
                _LMAAttribute = null;
5779
                ReleaseCOMObjects(_LMSymbol);
5780
                _LMSymbol = null;
5781
            }
5782

    
5783
            endList.Add(note);
5784
        }
5785

    
5786
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5787
        {
5788
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5789
            if (modelItem != null)
5790
            {
5791
                foreach (LMRepresentation rep in modelItem.Representations)
5792
                {
5793
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5794
                    {
5795
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5796
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5797
                        {
5798
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5799
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5800
                            if (modelItemIds.Count == 1)
5801
                            {
5802
                                string joinModelItemId = modelItemIds[0];
5803
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5804
                                if (survivorId != null)
5805
                                    break;
5806
                            }
5807
                        }
5808
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5809
                        {
5810
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5811
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5812
                            if (modelItemIds.Count == 1)
5813
                            {
5814
                                string joinModelItemId = modelItemIds[0];
5815
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5816
                                if (survivorId != null)
5817
                                    break;
5818
                            }
5819
                        }
5820
                    }
5821
                }
5822
            }
5823
        }
5824

    
5825
        /// <summary>
5826
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5827
        /// </summary>
5828
        /// <param name="x"></param>
5829
        /// <param name="y"></param>
5830
        /// <param name="originX"></param>
5831
        /// <param name="originY"></param>
5832
        /// <param name="SPPIDLabelLocation"></param>
5833
        /// <param name="location"></param>
5834
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5835
        {
5836
            if (location == Location.None)
5837
            {
5838
                x = originX;
5839
                y = originY;
5840
            }
5841
            else
5842
            {
5843
                if (location.HasFlag(Location.Center))
5844
                {
5845
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5846
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5847
                }
5848

    
5849
                if (location.HasFlag(Location.Left))
5850
                    x = SPPIDLabelLocation.X1;
5851
                else if (location.HasFlag(Location.Right))
5852
                    x = SPPIDLabelLocation.X2;
5853

    
5854
                if (location.HasFlag(Location.Down))
5855
                    y = SPPIDLabelLocation.Y1;
5856
                else if (location.HasFlag(Location.Up))
5857
                    y = SPPIDLabelLocation.Y2;
5858
            }
5859
        }
5860

    
5861
        /// <summary>
5862
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5863
        /// 1. Angle Valve
5864
        /// 2. 3개로 이루어진 Symbol Group
5865
        /// </summary>
5866
        /// <returns></returns>
5867
        private List<Symbol> GetPrioritySymbol()
5868
        {
5869
            DataTable symbolTable = document.SymbolTable;
5870
            // List에 순서대로 쌓는다.
5871
            List<Symbol> symbols = new List<Symbol>();
5872

    
5873
            // Angle Valve 부터
5874
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5875
            {
5876
                if (!symbols.Contains(symbol))
5877
                {
5878
                    double originX = 0;
5879
                    double originY = 0;
5880

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

    
5885
                    SlopeType slopeType1 = SlopeType.None;
5886
                    SlopeType slopeType2 = SlopeType.None;
5887
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5888
                    {
5889
                        double connectorX = 0;
5890
                        double connectorY = 0;
5891
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5892
                        if (slopeType1 == SlopeType.None)
5893
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5894
                        else
5895
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5896
                    }
5897

    
5898
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5899
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5900
                        symbols.Add(symbol);
5901
                }
5902
            }
5903

    
5904
            List<Symbol> tempSymbols = new List<Symbol>();
5905
            // Conn 갯수 기준
5906
            foreach (var item in document.SYMBOLS)
5907
            {
5908
                if (!symbols.Contains(item))
5909
                    tempSymbols.Add(item);
5910
            }
5911
            tempSymbols.Sort(SortSymbolPriority);
5912
            symbols.AddRange(tempSymbols);
5913

    
5914
            return symbols;
5915
        }
5916

    
5917
        private void SetPriorityLine(List<Line> lines)
5918
        {
5919
            lines.Sort(SortLinePriority);
5920

    
5921
            int SortLinePriority(Line a, Line b)
5922
            {
5923
                // Branch 없는것부터
5924
                int branchRetval = CompareBranchLine(a, b);
5925
                if (branchRetval != 0)
5926
                {
5927
                    return branchRetval;
5928
                }
5929
                else
5930
                {
5931
                    // Symbol 연결 갯수
5932
                    int connSymbolRetval = CompareConnSymbol(a, b);
5933
                    if (connSymbolRetval != 0)
5934
                    {
5935
                        return connSymbolRetval;
5936
                    }
5937
                    else
5938
                    {
5939
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5940
                        int connItemRetval = CompareConnItem(a, b);
5941
                        if (connItemRetval != 0)
5942
                        {
5943
                            return connItemRetval;
5944
                        }
5945
                        else
5946
                        {
5947
                            // ConnectedItem이 없는것
5948
                            int noneConnRetval = CompareNoneConn(a, b);
5949
                            if (noneConnRetval != 0)
5950
                            {
5951
                                return noneConnRetval;
5952
                            }
5953
                            else
5954
                            {
5955

    
5956
                            }
5957
                        }
5958
                    }
5959
                }
5960

    
5961
                return 0;
5962
            }
5963

    
5964
            int CompareNotSegmentLine(Line a, Line b)
5965
            {
5966
                List<Connector> connectorsA = a.CONNECTORS
5967
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5968
                    .ToList();
5969

    
5970
                List<Connector> connectorsB = b.CONNECTORS
5971
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5972
                    .ToList();
5973

    
5974
                // 오름차순
5975
                return connectorsB.Count.CompareTo(connectorsA.Count);
5976
            }
5977

    
5978
            int CompareConnSymbol(Line a, Line b)
5979
            {
5980
                List<Connector> connectorsA = a.CONNECTORS
5981
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5982
                    .ToList();
5983

    
5984
                List<Connector> connectorsB = b.CONNECTORS
5985
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5986
                    .ToList();
5987

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

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

    
6000
                List<Connector> connectorsB = b.CONNECTORS
6001
                    .Where(conn => conn.ConnectedObject != null &&
6002
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6003
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6004
                    .ToList();
6005

    
6006
                // 오름차순
6007
                return connectorsB.Count.CompareTo(connectorsA.Count);
6008
            }
6009

    
6010
            int CompareBranchLine(Line a, Line b)
6011
            {
6012
                List<Connector> connectorsA = a.CONNECTORS
6013
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6014
                    .ToList();
6015
                List<Connector> connectorsB = b.CONNECTORS
6016
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6017
                    .ToList();
6018

    
6019
                // 내림차순
6020
                return connectorsA.Count.CompareTo(connectorsB.Count);
6021
            }
6022

    
6023
            int CompareNoneConn(Line a, Line b)
6024
            {
6025
                List<Connector> connectorsA = a.CONNECTORS
6026
                    .Where(conn => conn.ConnectedObject == null)
6027
                    .ToList();
6028

    
6029
                List<Connector> connectorsB = b.CONNECTORS
6030
                    .Where(conn => conn.ConnectedObject == null)
6031
                    .ToList();
6032

    
6033
                // 오름차순
6034
                return connectorsB.Count.CompareTo(connectorsA.Count);
6035
            }
6036
        }
6037

    
6038
        private void SortText(List<Text> texts)
6039
        {
6040
            texts.Sort(Sort);
6041

    
6042
            int Sort(Text a, Text b)
6043
            {
6044
                int yRetval = CompareY(a, b);
6045
                if (yRetval != 0)
6046
                {
6047
                    return yRetval;
6048
                }
6049
                else
6050
                {
6051
                    return CompareX(a, b);
6052
                }
6053
            }
6054

    
6055
            int CompareY(Text a, Text b)
6056
            {
6057
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6058
            }
6059

    
6060
            int CompareX(Text a, Text b)
6061
            {
6062
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6063
            }
6064
        }
6065
        private void SortNote(List<Note> notes)
6066
        {
6067
            notes.Sort(Sort);
6068

    
6069
            int Sort(Note a, Note b)
6070
            {
6071
                int yRetval = CompareY(a, b);
6072
                if (yRetval != 0)
6073
                {
6074
                    return yRetval;
6075
                }
6076
                else
6077
                {
6078
                    return CompareX(a, b);
6079
                }
6080
            }
6081

    
6082
            int CompareY(Note a, Note b)
6083
            {
6084
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6085
            }
6086

    
6087
            int CompareX(Note a, Note b)
6088
            {
6089
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6090
            }
6091
        }
6092

    
6093
        private void SortBranchLines()
6094
        {
6095
            BranchLines.Sort(SortBranchLine);
6096
            int SortBranchLine(Line a, Line b)
6097
            {
6098
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6099
                 x.ConnectedObject.GetType() == typeof(Line) &&
6100
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6101
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6102

    
6103
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6104
                 x.ConnectedObject.GetType() == typeof(Line) &&
6105
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6106
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6107

    
6108
                // 내림차순
6109
                return countA.CompareTo(countB);
6110
            }
6111
        }
6112

    
6113
        private static int SortSymbolPriority(Symbol a, Symbol b)
6114
        {
6115
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6116
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6117
            int retval = countB.CompareTo(countA);
6118
            if (retval != 0)
6119
                return retval;
6120
            else
6121
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6122
        }
6123

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

    
6138
        private string GetSPPIDFileName(string modelItemId)
6139
        {
6140
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6141
            string symbolPath = null;
6142
            foreach (LMRepresentation rep in modelItem.Representations)
6143
            {
6144
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6145
                {
6146
                    symbolPath = rep.get_FileName();
6147
                    break;
6148
                }
6149
            }
6150
            ReleaseCOMObjects(modelItem);
6151
            return symbolPath;
6152
        }
6153

    
6154
        /// <summary>
6155
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6156
        /// </summary>
6157
        /// <param name="graphicOID"></param>
6158
        /// <param name="milliseconds"></param>
6159
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6160
        {
6161
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6162
            {
6163
                double minX = 0;
6164
                double minY = 0;
6165
                double maxX = 0;
6166
                double maxY = 0;
6167
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6168
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6169

    
6170
                Thread.Sleep(milliseconds);
6171
            }
6172
        }
6173

    
6174
        /// <summary>
6175
        /// ComObject를 Release
6176
        /// </summary>
6177
        /// <param name="objVars"></param>
6178
        public void ReleaseCOMObjects(params object[] objVars)
6179
        {
6180
            if (objVars != null)
6181
            {
6182
                int intNewRefCount = 0;
6183
                foreach (object obj in objVars)
6184
                {
6185
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6186
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6187
                }
6188
            }
6189
        }
6190

    
6191
        /// IDisposable 구현
6192
        ~AutoModeling()
6193
        {
6194
            this.Dispose(false);
6195
        }
6196

    
6197
        private bool disposed;
6198
        public void Dispose()
6199
        {
6200
            this.Dispose(true);
6201
            GC.SuppressFinalize(this);
6202
        }
6203

    
6204
        protected virtual void Dispose(bool disposing)
6205
        {
6206
            if (this.disposed) return;
6207
            if (disposing)
6208
            {
6209
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6210
            }
6211
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6212
            this.disposed = true;
6213
        }
6214
    }
6215
}
클립보드 이미지 추가 (최대 크기: 500 MB)