프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 8018a77a

이력 | 보기 | 이력해설 | 다운로드 (287 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Data;
7
using Llama;
8
using Plaice;
9
using Ingr.RAD2D.Interop.RAD2D;
10
using Ingr.RAD2D.Internal;
11
using Ingr.RAD2D.Helper;
12
using Converter.BaseModel;
13
using Converter.SPPID.Model;
14
using Converter.SPPID.Properties;
15
using Converter.SPPID.Util;
16
using Converter.SPPID.DB;
17
using Ingr.RAD2D.MacroControls.CmdCtrl;
18
using Ingr.RAD2D;
19
using System.Windows;
20
using System.Threading;
21
using System.Drawing;
22
using Microsoft.VisualBasic;
23
using Newtonsoft.Json;
24
using DevExpress.XtraSplashScreen;
25
namespace Converter.SPPID
26
{
27
    public class AutoModeling : IDisposable
28
    {
29
        Placement _placement;
30
        LMADataSource dataSource;
31
        string drawingID;
32
        dynamic newDrawing;
33
        dynamic application;
34
        bool closeDocument;
35
        Ingr.RAD2D.Application radApp;
36
        SPPID_Document document;
37
        ETCSetting _ETCSetting;
38

    
39
        public string DocumentLabelText { get; set; }
40

    
41
        List<Line> BranchLines = new List<Line>();
42
        List<string> ZeroLengthSymbolToSymbolModelItemID = new List<string>();
43
        List<string> ZeroLengthModelItemID = new List<string>();
44
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
45
        List<Symbol> prioritySymbols;
46
        List<string> FlowMarkRepIds = new List<string>();
47

    
48
        public AutoModeling(SPPID_Document document, bool closeDocument)
49
        {
50
            application = Interaction.GetObject("", "PIDAutomation.Application");
51
            WrapperApplication wApp = new WrapperApplication(application.Application);
52
            radApp = wApp.RADApplication;
53

    
54
            this.closeDocument = closeDocument;
55
            this.document = document;
56
            this._ETCSetting = ETCSetting.GetInstance();
57
        }
58

    
59
        private void SetSystemEditingCommand(bool value)
60
        {
61
            foreach (var item in radApp.Commands)
62
            {
63
                if (item.Argument == "SystemEditingCmd.SystemEditing")
64
                {
65
                    if (item.Checked != value)
66
                    {
67
                        radApp.RunMacro("systemeditingcmd.dll");
68
                        break;
69
                    }
70

    
71
                }
72
            }
73
        }
74

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

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

    
136
                    // Result Logging
137
                    document.CheckModelingResult();
138
                }
139
            }
140
            catch (Exception ex)
141
            {
142
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
143
                {
144
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
145
                    SplashScreenManager.CloseForm(false);
146
                    Log.Write("\r\n");
147
                }
148
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
149
            }
150
            finally
151
            {
152
                Project_DB.InsertDrawingInfoAndOPCInfo(document.PATH, drawingNumber, drawingName, document);
153
                //Project_DB.InsertLineNumberInfo(document.PATH, drawingNumber, drawingName, document);
154

    
155
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
156
                {
157
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
158
                    SplashScreenManager.CloseForm(false);
159
                    Log.Write("\r\n");
160
                }
161
                Thread.Sleep(1000);
162

    
163
                Log.Write("End Modeling");
164
                radApp.ActiveWindow.Fit();
165

    
166
                ReleaseCOMObjects(application);
167
                application = null;
168
                if (radApp.ActiveDocument != null)
169
                {
170
                    if (closeDocument && newDrawing != null)
171
                    {
172
                        newDrawing.Save();
173
                        newDrawing.CloseDrawing(true);
174
                        ReleaseCOMObjects(newDrawing);
175
                        newDrawing = null;
176
                    }
177
                    else if (newDrawing == null)
178
                    {
179
                        Log.Write("error document");
180
                    }
181
                }
182

    
183
                ReleaseCOMObjects(dataSource);
184
                dataSource = null;
185
                ReleaseCOMObjects(_placement);
186
                _placement = null;
187

    
188
                Thread.Sleep(1000);
189
            }
190
        }
191

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1079
                        drawingAttributeDT.Dispose();
1080
                    }
1081

    
1082
                    ReleaseCOMObjects(drawing);
1083
                }
1084

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

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

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

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

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

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

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

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

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

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

    
1197
        /// <summary>
1198
        /// 심볼을 실제로 Modeling 메서드
1199
        /// </summary>
1200
        /// <param name="symbol">생성할 심볼</param>
1201
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1202
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1203
        {
1204
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1205
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1206
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1207
                return;
1208
            // 이미 모델링 됐을 경우
1209
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1210
                return;
1211

    
1212
            LMSymbol _LMSymbol = null;
1213

    
1214
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1215
            double x = symbol.SPPID.ORIGINAL_X;
1216
            double y = symbol.SPPID.ORIGINAL_Y;
1217
            int mirror = 0;
1218
            double angle = symbol.ANGLE;
1219

    
1220
            // OPC 일경우 180도 일때 Mirror
1221
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1222
                mirror = 1;
1223

    
1224
            // Mirror 계산
1225
            if (symbol.FLIP == 1)
1226
            {
1227
                mirror = 1;
1228
                angle += Math.PI;
1229
            }
1230

    
1231
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1232
            {
1233
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1234
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1235
                if (connector != null)
1236
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1237

    
1238
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1239
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1240
                if (temp != null)
1241
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1242
                ReleaseCOMObjects(temp);
1243
                temp = null;
1244

    
1245
                if (_LMSymbol != null && _TargetItem != null)
1246
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1247

    
1248
                ReleaseCOMObjects(_TargetItem);
1249
            }
1250
            else
1251
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1252

    
1253
            if (_LMSymbol != null)
1254
            {
1255
                _LMSymbol.Commit();
1256

    
1257
                // ConnCheck
1258
                List<string> ids = new List<string>();
1259
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1260
                {
1261
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1262
                        ids.Add(item.Id);
1263
                    ReleaseCOMObjects(item);
1264
                }
1265
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1266
                {
1267
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1268
                        ids.Add(item.Id);
1269
                    ReleaseCOMObjects(item);
1270
                }
1271

    
1272
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1273
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1274
                {
1275
                    double currentX = _LMSymbol.get_XCoordinate();
1276
                    double currentY = _LMSymbol.get_YCoordinate();
1277

    
1278

    
1279
                }
1280

    
1281
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1282
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1283
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1284

    
1285
                foreach (var item in symbol.ChildSymbols)
1286
                    CreateChildSymbol(item, _LMSymbol, symbol);
1287

    
1288
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1289
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1290

    
1291
                double[] range = null;
1292
                GetSPPIDSymbolRange(symbol, ref range);
1293
                symbol.SPPID.SPPID_Min_X = range[0];
1294
                symbol.SPPID.SPPID_Min_Y = range[1];
1295
                symbol.SPPID.SPPID_Max_X = range[2];
1296
                symbol.SPPID.SPPID_Max_Y = range[3];
1297

    
1298
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1299
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1300
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1301
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1302

    
1303
                ReleaseCOMObjects(_LMSymbol);
1304
            }
1305
        }
1306
        /// <summary>
1307
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1308
        /// Signal Point는 고려하지 않음
1309
        /// </summary>
1310
        /// <param name="symbol"></param>
1311
        /// <param name="_TargetItem"></param>
1312
        /// <param name="targetX"></param>
1313
        /// <param name="targetY"></param>
1314
        /// <returns></returns>
1315
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1316
        {
1317
            LMConnector tempConnector = null;
1318

    
1319
            List<Symbol> group = new List<Symbol>();
1320
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1321
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1322
            {
1323
                List<Connector> connectors = new List<Connector>();
1324
                foreach (var item in group)
1325
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1326
                /// Primary or Secondary Type Line만 고려
1327
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1328
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1329
                if (_connector != null)
1330
                {
1331
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1332
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1333
                    /// PipingPoint가 2개 이상만
1334
                    if (pointInfos.Count >= 2)
1335
                    {
1336
                        double lineX = 0;
1337
                        double lineY = 0;
1338
                        double length = 0;
1339
                        foreach (var item in pointInfos)
1340
                        {
1341
                            double tempX = item[1];
1342
                            double tempY = item[2];
1343

    
1344
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1345
                            if (calcDistance > length)
1346
                            {
1347
                                lineX = tempX;
1348
                                lineY = tempY;
1349
                            }
1350
                        }
1351

    
1352
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1353
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1354
                        placeRunInputs.AddPoint(-1, -1);
1355
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1356
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1357
                        if (tempConnector != null)
1358
                            tempConnector.Commit();
1359
                        ReleaseCOMObjects(_LMAItem);
1360
                        _LMAItem = null;
1361
                        ReleaseCOMObjects(placeRunInputs);
1362
                        placeRunInputs = null;
1363
                    }
1364
                }
1365
            }
1366

    
1367
            return tempConnector;
1368
        }
1369
        /// <summary>
1370
        /// Symbol의 PipingPoints를 구함
1371
        /// SignalPoint는 고려하지 않음
1372
        /// </summary>
1373
        /// <param name="symbol"></param>
1374
        /// <returns></returns>
1375
        private List<double[]> getPipingPoints(LMSymbol symbol)
1376
        {
1377
            LMModelItem modelItem = symbol.ModelItemObject;
1378
            LMPipingPoints pipingPoints = null;
1379
            if (modelItem.get_ItemTypeName() == "PipingComp")
1380
            {
1381
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1382
                pipingPoints = pipingComp.PipingPoints;
1383
                ReleaseCOMObjects(pipingComp);
1384
                pipingComp = null;
1385
            }
1386
            else if (modelItem.get_ItemTypeName() == "Instrument")
1387
            {
1388
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1389
                pipingPoints = instrument.PipingPoints;
1390
                ReleaseCOMObjects(instrument);
1391
                instrument = null;
1392
            }
1393
            else
1394
                Log.Write("다른 Type");
1395

    
1396
            List<double[]> info = new List<double[]>();
1397
            if (pipingPoints != null)
1398
            {
1399
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1400
                {
1401
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1402
                    {
1403
                        if (attribute.Name == "PipingPointNumber")
1404
                        {
1405
                            int index = Convert.ToInt32(attribute.get_Value());
1406
                            if (info.Find(loopX => loopX[0] == index) == null)
1407
                            {
1408
                                double x = 0;
1409
                                double y = 0;
1410
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1411
                                    info.Add(new double[] { index, x, y });
1412
                            }
1413
                        }
1414
                    }
1415
                }
1416
            }
1417
            ReleaseCOMObjects(modelItem);
1418
            modelItem = null;
1419
            ReleaseCOMObjects(pipingPoints);
1420
            pipingPoints = null;
1421

    
1422
            return info;
1423
        }
1424

    
1425
        private void RemoveSymbol(Symbol symbol)
1426
        {
1427
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1428
            {
1429
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1430
                if (_LMSymbol != null)
1431
                {
1432
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1433
                    ReleaseCOMObjects(_LMSymbol);
1434
                }
1435
            }
1436

    
1437
            symbol.SPPID.RepresentationId = string.Empty;
1438
            symbol.SPPID.ModelItemID = string.Empty;
1439
            symbol.SPPID.SPPID_X = double.NaN;
1440
            symbol.SPPID.SPPID_Y = double.NaN;
1441
            symbol.SPPID.SPPID_Min_X = double.NaN;
1442
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1443
            symbol.SPPID.SPPID_Max_X = double.NaN;
1444
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1445
        }
1446

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

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

    
1472
        /// <summary>
1473
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1474
        /// </summary>
1475
        /// <param name="targetConnector"></param>
1476
        /// <param name="targetSymbol"></param>
1477
        /// <param name="x"></param>
1478
        /// <param name="y"></param>
1479
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1480
        {
1481
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1482

    
1483
            double[] range = null;
1484
            List<double[]> points = new List<double[]>();
1485
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1486
            double x1 = range[0];
1487
            double y1 = range[1];
1488
            double x2 = range[2];
1489
            double y2 = range[3];
1490

    
1491
            // Origin 기준 Connector의 위치차이
1492
            double sceneX = 0;
1493
            double sceneY = 0;
1494
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1495
            double originX = 0;
1496
            double originY = 0;
1497
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1498
            double gapX = originX - sceneX;
1499
            double gapY = originY - sceneY;
1500

    
1501
            // SPPID Symbol과 ID2 심볼의 크기 차이
1502
            double sizeWidth = 0;
1503
            double sizeHeight = 0;
1504
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1505
            if (sizeWidth == 0 || sizeHeight == 0)
1506
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1507

    
1508
            double percentX = (x2 - x1) / sizeWidth;
1509
            double percentY = (y2 - y1) / sizeHeight;
1510

    
1511
            double SPPIDgapX = gapX * percentX;
1512
            double SPPIDgapY = gapY * percentY;
1513

    
1514
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1515
            double distance = double.MaxValue;
1516
            double[] resultPoint;
1517
            foreach (var point in points)
1518
            {
1519
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1520
                if (distance > result)
1521
                {
1522
                    distance = result;
1523
                    resultPoint = point;
1524
                    x = point[0];
1525
                    y = point[1];
1526
                }
1527
            }
1528

    
1529
            ReleaseCOMObjects(_TargetItem);
1530
        }
1531

    
1532
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1533
        {
1534
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1535
            if (index == 0)
1536
            {
1537
                x = targetLine.SPPID.START_X;
1538
                y = targetLine.SPPID.START_Y;
1539
            }
1540
            else
1541
            {
1542
                x = targetLine.SPPID.END_X;
1543
                y = targetLine.SPPID.END_Y;
1544
            }
1545
        }
1546

    
1547
        /// <summary>
1548
        /// SPPID Symbol의 Range를 구한다.
1549
        /// </summary>
1550
        /// <param name="symbol"></param>
1551
        /// <param name="range"></param>
1552
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1553
        {
1554
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1555
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1556
            double x1 = 0;
1557
            double y1 = 0;
1558
            double x2 = 0;
1559
            double y2 = 0;
1560
            symbol2d.Range(out x1, out y1, out x2, out y2);
1561
            range = new double[] { x1, y1, x2, y2 };
1562

    
1563
            for (int i = 1; i < int.MaxValue; i++)
1564
            {
1565
                double connX = 0;
1566
                double connY = 0;
1567
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1568
                    points.Add(new double[] { connX, connY });
1569
                else
1570
                    break;
1571
            }
1572

    
1573
            foreach (var childSymbol in symbol.ChildSymbols)
1574
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1575

    
1576
            ReleaseCOMObjects(_TargetItem);
1577
        }
1578

    
1579
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1580
        {
1581
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1582
            if (_TargetItem != null)
1583
            {
1584
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1585
                double x1 = 0;
1586
                double y1 = 0;
1587
                double x2 = 0;
1588
                double y2 = 0;
1589
                if (!bForGraphic)
1590
                {
1591
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1592
                    range = new double[] { x1, y1, x2, y2 };
1593
                }
1594
                else
1595
                {
1596
                    x1 = double.MaxValue;
1597
                    y1 = double.MaxValue;
1598
                    x2 = double.MinValue;
1599
                    y2 = double.MinValue;
1600
                    range = new double[] { x1, y1, x2, y2 };
1601

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

    
1663
                if (!bOnlySymbol)
1664
                {
1665
                    foreach (var childSymbol in symbol.ChildSymbols)
1666
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1667
                }
1668
                ReleaseCOMObjects(_TargetItem);
1669
            }
1670
        }
1671

    
1672
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1673
        {
1674
            if (labelPersist != null)
1675
            {
1676
                double x1 = double.MaxValue;
1677
                double y1 = double.MaxValue;
1678
                double x2 = double.MinValue;
1679
                double y2 = double.MinValue;
1680
                range = new double[] { x1, y1, x2, y2 };
1681

    
1682
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1683
                foreach (var item in dependency.DrawingObjects)
1684
                {
1685
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1686
                    if (textBox != null)
1687
                    {
1688
                        if (dependency != null)
1689
                        {
1690
                            double tempX1;
1691
                            double tempY1;
1692
                            double tempX2;
1693
                            double tempY2;
1694
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1695
                            x1 = Math.Min(x1, tempX1);
1696
                            y1 = Math.Min(y1, tempY1);
1697
                            x2 = Math.Max(x2, tempX2);
1698
                            y2 = Math.Max(y2, tempY2);
1699

    
1700
                            range = new double[] { x1, y1, x2, y2 };
1701
                        }
1702
                    }
1703
                }
1704
                
1705
            }
1706
        }
1707

    
1708
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1709
        {
1710
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1711
            foreach (var symbol in symbols)
1712
            {
1713
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1714
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1715
                double x1 = 0;
1716
                double y1 = 0;
1717
                double x2 = 0;
1718
                double y2 = 0;
1719
                symbol2d.Range(out x1, out y1, out x2, out y2);
1720

    
1721
                tempRange[0] = Math.Min(tempRange[0], x1);
1722
                tempRange[1] = Math.Min(tempRange[1], y1);
1723
                tempRange[2] = Math.Max(tempRange[2], x2);
1724
                tempRange[3] = Math.Max(tempRange[3], y2);
1725

    
1726
                foreach (var childSymbol in symbol.ChildSymbols)
1727
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1728

    
1729
                ReleaseCOMObjects(_TargetItem);
1730
            }
1731

    
1732
            range = tempRange;
1733
        }
1734

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

    
1756
                for (int i = 1; i < int.MaxValue; i++)
1757
                {
1758
                    double connX = 0;
1759
                    double connY = 0;
1760
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1761
                        points.Add(new double[] { connX, connY });
1762
                    else
1763
                        break;
1764
                }
1765

    
1766
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1767
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1768

    
1769
                ReleaseCOMObjects(_ChildSymbol);
1770
            }
1771
        }
1772

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

    
1789
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1790
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1791
                ReleaseCOMObjects(_ChildSymbol);
1792
            }
1793
        }
1794

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

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

    
1828
                        // Target Symbol Item 가져오고 Label Modeling
1829
                        LMSymbol _TargetItem = dataSource.GetSymbol(sRep);
1830
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: _TargetItem.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1831

    
1832
                        //Leader 선 센터로
1833
                        if (_LMLabelPresist != null)
1834
                        {
1835
                            // Target Item에 Label의 Attribute Input
1836
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1837

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

    
1866
                                        if (result)
1867
                                            break;
1868
                                    }
1869

    
1870
                                    if (result)
1871
                                        break;
1872
                                }
1873
                            }
1874

    
1875
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1876
                            _LMLabelPresist.Commit();
1877
                            ReleaseCOMObjects(_LMLabelPresist);
1878
                        }
1879

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

    
1896
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1897
                        if (_LMLabelPresist != null)
1898
                        {
1899
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1900
                            _LMLabelPresist.Commit();
1901
                            ReleaseCOMObjects(_LMLabelPresist);
1902
                        }
1903
                        ReleaseCOMObjects(connectedLMConnector);
1904
                    }
1905

    
1906
                    foreach (var item in connectorVertices)
1907
                        if (item.Key != null)
1908
                            ReleaseCOMObjects(item.Key);
1909
                }
1910
            }
1911
        }
1912

    
1913
        /// <summary>
1914
        /// Equipment를 실제로 Modeling 메서드
1915
        /// </summary>
1916
        /// <param name="equipment"></param>
1917
        private void EquipmentModeling(Equipment equipment)
1918
        {
1919
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1920
                return;
1921

    
1922
            LMSymbol _LMSymbol = null;
1923
            LMSymbol targetItem = null;
1924
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1925
            double x = equipment.SPPID.ORIGINAL_X;
1926
            double y = equipment.SPPID.ORIGINAL_Y;
1927
            int mirror = 0;
1928
            double angle = equipment.ANGLE;
1929

    
1930
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1931

    
1932
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1933
            if (connector != null)
1934
            {
1935
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1936
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1937
                if (connEquipment != null)
1938
                {
1939
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1940
                        EquipmentModeling(connEquipment);
1941

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

    
1976
            if (_LMSymbol != null)
1977
            {
1978
                _LMSymbol.Commit();
1979
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1980
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1981
                ReleaseCOMObjects(_LMSymbol);
1982
            }
1983

    
1984
            if (targetItem != null)
1985
            {
1986
                ReleaseCOMObjects(targetItem);
1987
            }
1988

    
1989
            ReleaseCOMObjects(_LMSymbol);
1990
        }
1991

    
1992
        private void VendorPackageModeling(VendorPackage vendorPackage)
1993
        {
1994
            ETCSetting setting = ETCSetting.GetInstance();
1995
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1996
            {
1997
                string symbolPath = setting.VendorPackageSymbolPath;
1998
                double x = vendorPackage.SPPID.ORIGINAL_X;
1999
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2000

    
2001
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2002
                if (symbol != null)
2003
                {
2004
                    symbol.Commit();
2005
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2006
                }
2007

    
2008
                ReleaseCOMObjects(symbol);
2009
                symbol = null;
2010
            }
2011
        }
2012

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

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

    
2049
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
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
                    if (!endObjects.Contains(connItem))
2057
                    {
2058
                        endObjects.Add(connItem);
2059
                        if (connItem.GetType() == typeof(Symbol))
2060
                        {
2061
                            Symbol connSymbol = connItem as Symbol;
2062
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2063
                            {
2064
                                SymbolModeling(connSymbol, symbol);
2065
                            }
2066
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2067
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2068
                        }
2069
                        else if (connItem.GetType() == typeof(Line))
2070
                        {
2071
                            Line connLine = connItem as Line;
2072
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2073
                        }
2074
                    }
2075
                }
2076
            }
2077
        }
2078

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

    
2099
                                List<Symbol> group = new List<Symbol>();
2100
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2101
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2102
                                List<Symbol> endModelingGroup = new List<Symbol>();
2103
                                if (priority != null)
2104
                                {
2105
                                    SymbolGroupModeling(priority, group);
2106

    
2107
                                    // Range 겹치는지 확인해야함
2108
                                    double[] prevRange = null;
2109
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2110
                                    double[] groupRange = null;
2111
                                    GetSPPIDSymbolRange(group, ref groupRange);
2112

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

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

    
2146
                                                SymbolGroupModeling(priority, group);
2147
                                            }
2148
                                        }
2149
                                    }
2150
                                }
2151
                                else
2152
                                {
2153
                                    SymbolModeling(connSymbol, null);
2154
                                    // Range 겹치는지 확인해야함
2155
                                    double[] prevRange = null;
2156
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2157
                                    double[] connRange = null;
2158
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2159

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

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

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

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

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

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

    
2261

    
2262
            ReleaseCOMObjects(_LMSymbol);
2263
        }
2264
        double index = 0;
2265
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2266
        {
2267
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2268
                return;
2269

    
2270
            List<Line> group = new List<Line>();
2271
            GetConnectedLineGroup(line, group);
2272
            LineCoordinateCorrection(group);
2273

    
2274
            foreach (var groupLine in group)
2275
            {
2276
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2277
                {
2278
                    BranchLines.Add(groupLine);
2279
                    continue;
2280
                }
2281

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

    
2355
                            placeRunInputs.AddPoint(x, y);
2356

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

    
2377
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2378
                if (_lMConnector != null)
2379
                {
2380
                    _lMConnector.Commit();
2381
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2382

    
2383
                    bool bRemodelingStart = false;
2384
                    if (_LMSymbolStart != null)
2385
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2386
                    bool bRemodelingEnd = false;
2387
                    if (_LMSymbolEnd != null)
2388
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2389

    
2390
                    if (bRemodelingStart || bRemodelingEnd)
2391
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2392

    
2393
                    FlowMarkModeling(groupLine);
2394

    
2395
                    ReleaseCOMObjects(_lMConnector);
2396

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

    
2413
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2414
                x.ConnectedObject != null &&
2415
                x.ConnectedObject.GetType() == typeof(Line) &&
2416
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2417
                .Select(x => x.ConnectedObject)
2418
                .ToList();
2419

    
2420
                foreach (var item in removeLines)
2421
                    RemoveLineForModeling(item as Line);
2422

    
2423
                ReleaseCOMObjects(_LMAItem);
2424
                _LMAItem = null;
2425
                ReleaseCOMObjects(placeRunInputs);
2426
                placeRunInputs = null;
2427
                ReleaseCOMObjects(_LMSymbolStart);
2428
                _LMSymbolStart = null;
2429
                ReleaseCOMObjects(_LMSymbolEnd);
2430
                _LMSymbolEnd = null;
2431

    
2432
                if (isBranchModeling && BranchLines.Contains(groupLine))
2433
                    BranchLines.Remove(groupLine);
2434
            }
2435
        }
2436

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

    
2498
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2499
            if (_lMConnector != null)
2500
                _lMConnector.Commit();
2501

    
2502
            ReleaseCOMObjects(_LMAItem);
2503
            _LMAItem = null;
2504
            ReleaseCOMObjects(placeRunInputs);
2505
            placeRunInputs = null;
2506
            ReleaseCOMObjects(_LMSymbolStart);
2507
            _LMSymbolStart = null;
2508
            ReleaseCOMObjects(_LMSymbolEnd);
2509
            _LMSymbolEnd = null;
2510

    
2511
            return _lMConnector;
2512
        }
2513

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

    
2542
                ReleaseCOMObjects(modelItem);
2543
            }
2544
        }
2545

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

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

    
2585
        private void LineCoordinateCorrection(List<Line> group)
2586
        {
2587
            // 순서대로 전 Item 기준 정렬
2588
            LineCoordinateCorrectionByStart(group);
2589

    
2590
            // 역으로 심볼이 있을 경우 좌표 보정
2591
            LineCoordinateCorrectionForLastLine(group);
2592
        }
2593

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

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

    
2624
                    // 같으면 보정
2625
                    if (line.SlopeType == prevLine.SlopeType)
2626
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2627
                    else
2628
                    {
2629
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2630
                        {
2631
                            double prevX = 0;
2632
                            double prevY = 0;
2633
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2634
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2635

    
2636
                            double x = 0;
2637
                            double y = 0;
2638
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2639
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2640
                        }
2641
                        else if (line.SlopeType == SlopeType.VERTICAL)
2642
                        {
2643
                            double prevX = 0;
2644
                            double prevY = 0;
2645
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2646
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2647

    
2648
                            double x = 0;
2649
                            double y = 0;
2650
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2651
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2652
                        }
2653
                        break;
2654
                    }
2655
                }
2656
            }
2657
        }
2658

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

    
2678
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2679
        }
2680

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

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

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

    
2741
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2742
        {
2743
            if (symbol != null)
2744
            {
2745
                string repID = symbol.AsLMRepresentation().Id;
2746
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2747
                string lineUID = line.UID;
2748

    
2749
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2750
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2751
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2752

    
2753
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2754
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2755
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2756

    
2757
                if (startSpecBreak != null || startEndBreak != null)
2758
                    result = true;
2759
            }
2760
        }
2761

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

    
2788
            List<double[]> vertices = new List<double[]>();
2789
            for (int i = 1; i <= verticesCount; i++)
2790
            {
2791
                double x = 0;
2792
                double y = 0;
2793
                lineStringGeometry.GetVertex(i, ref x, ref y);
2794
                vertices.Add(new double[] { x, y });
2795
            }
2796

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

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

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

    
2850
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2851
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2852

    
2853
            ReleaseCOMObjects(placeRunInputs);
2854
            ReleaseCOMObjects(_LMAItem);
2855
            ReleaseCOMObjects(modelItem);
2856

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

    
2878
                if (endSymbol != null && bEnd)
2879
                {
2880
                    if (startSymbol != null)
2881
                    {
2882
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2883
                        newConnector = dicVertices.First().Key;
2884
                    }
2885

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

    
2902
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2903
                ReleaseCOMObjects(newConnector);
2904
            }
2905

    
2906
            ReleaseCOMObjects(modelItem);
2907
        }
2908

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

    
2931
                    if (result)
2932
                        break;
2933
                }
2934
            }
2935
            foreach (var item in dicVertices)
2936
                ReleaseCOMObjects(item.Key);
2937
        }
2938

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

    
2964
                            if (child != null)
2965
                                break;
2966
                        }
2967

    
2968
                        if (child != null)
2969
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2970
                    }
2971

    
2972
                    break;
2973
                }
2974
            }
2975

    
2976
            return _LMSymbol;
2977
        }
2978

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

    
2995
            return null;
2996
        }
2997

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

    
3007
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3008
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3009
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3010

    
3011
            if (targetLMConnector != null)
3012
            {
3013
                // LEADER Line 검사
3014
                bool leaderLine = false;
3015
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3016
                if (symbolMapping != null)
3017
                    leaderLine = symbolMapping.LEADERLINE;
3018

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

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

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

    
3067
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3068
            {
3069
                double[] vertices = null;
3070
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3071
                double x = 0;
3072
                double y = 0;
3073
                lineStringGeometry.GetVertex(1, ref x, ref y);
3074

    
3075
                string flowDirection = string.Empty;
3076
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3077
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3078
                    flowDirection = flowAttribute.get_Value().ToString();
3079

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

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

    
3119
            return newConnector;
3120
        }
3121

    
3122
        /// <summary>
3123
        /// SpecBreak Modeling 메서드
3124
        /// </summary>
3125
        /// <param name="specBreak"></param>
3126
        private void SpecBreakModeling(SpecBreak specBreak)
3127
        {
3128
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3129
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3130

    
3131
            if (upStreamObj != null &&
3132
                downStreamObj != null)
3133
            {
3134
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3135
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3136
                    targetLMConnector != null && 
3137
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3138
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3139

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

    
3156
                            if (_LmLabelPersist != null)
3157
                            {
3158
                                _LmLabelPersist.Commit();
3159
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3160
                                if (_LmLabelPersist.ModelItemObject != null)
3161
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3162
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3163
                                ReleaseCOMObjects(_LmLabelPersist);
3164
                            }
3165

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

    
3180
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3181
        {
3182
            LMConnector targetConnector = null;
3183
            Symbol targetSymbol = targetObj as Symbol;
3184
            Symbol connectedSymbol = connectedObj as Symbol;
3185
            Line targetLine = targetObj as Line;
3186
            Line connectedLine = connectedObj as Line;
3187
            if (targetSymbol != null && connectedSymbol != null)
3188
            {
3189
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3190
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3191

    
3192
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3193
                {
3194
                    if (connector.get_ItemStatus() != "Active")
3195
                        continue;
3196

    
3197
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3198
                    {
3199
                        targetConnector = connector;
3200
                        break;
3201
                    }
3202
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3203
                    {
3204
                        targetConnector = connector;
3205
                        break;
3206
                    }
3207
                }
3208

    
3209
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3210
                {
3211
                    if (connector.get_ItemStatus() != "Active")
3212
                        continue;
3213

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

    
3226
                ReleaseCOMObjects(targetLMSymbol);
3227
                ReleaseCOMObjects(connectedLMSymbol);
3228
            }
3229
            else if (targetLine != null && connectedLine != null)
3230
            {
3231
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3232
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3233

    
3234
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3235
                {
3236
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3237
                    {
3238
                        if (targetConnector != null)
3239
                            break;
3240

    
3241
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3242
                        {
3243
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3244

    
3245
                            if (IsConnected(_LMConnector, connectedModelItem))
3246
                                targetConnector = _LMConnector;
3247
                            else
3248
                                ReleaseCOMObjects(_LMConnector);
3249
                        }
3250
                    }
3251

    
3252
                    ReleaseCOMObjects(targetModelItem);
3253
                }
3254
            }
3255
            else
3256
            {
3257
                LMSymbol connectedLMSymbol = null;
3258
                if (connectedSymbol != null)
3259
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3260
                else if (targetSymbol != null)
3261
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3262
                else
3263
                {
3264

    
3265
                }
3266
                LMModelItem targetModelItem = null;
3267
                if (targetLine != null)
3268
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3269
                else if (connectedLine != null)
3270
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3271
                else
3272
                {
3273

    
3274
                }
3275
                if (connectedLMSymbol != null && targetModelItem != null)
3276
                {
3277
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3278
                    {
3279
                        if (connector.get_ItemStatus() != "Active")
3280
                            continue;
3281

    
3282
                        if (IsConnected(connector, targetModelItem))
3283
                        {
3284
                            targetConnector = connector;
3285
                            break;
3286
                        }
3287
                    }
3288

    
3289
                    if (targetConnector == null)
3290
                    {
3291
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3292
                        {
3293
                            if (connector.get_ItemStatus() != "Active")
3294
                                continue;
3295

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

    
3305
            }
3306

    
3307
            return targetConnector;
3308
        }
3309

    
3310
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3311
        {
3312
            double[] result = null;
3313
            Line targetLine = targetObj as Line;
3314
            Symbol targetSymbol = targetObj as Symbol;
3315
            Line connLine = connObj as Line;
3316
            Symbol connSymbol = connObj as Symbol;
3317

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

    
3356
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3357

    
3358
                    ReleaseCOMObjects(modelItem);
3359
                    ReleaseCOMObjects(connectedConnector);
3360

    
3361
                    if (vertices.Count > 0)
3362
                    {
3363
                        if (connIndex == 1)
3364
                            result = vertices[0];
3365
                        else if (connIndex == 2)
3366
                            result = vertices[vertices.Count - 1];
3367

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

    
3417
            return result;
3418
        }
3419

    
3420
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3421
        {
3422
            bool result = false;
3423

    
3424
            foreach (LMRepresentation rep in modelItem.Representations)
3425
            {
3426
                if (result)
3427
                    break;
3428

    
3429
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3430
                {
3431
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3432

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

    
3466
                    ReleaseCOMObjects(_LMConnector);
3467
                }
3468
            }
3469

    
3470

    
3471
            return result;
3472
        }
3473

    
3474
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3475
        {
3476
            foreach (LMRepresentation rep in modelItem.Representations)
3477
            {
3478
                if (connectedConnector != null)
3479
                    break;
3480

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

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

    
3518
                    if (connectedConnector == null)
3519
                        ReleaseCOMObjects(_LMConnector);
3520
                }
3521
            }
3522
        }
3523

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

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

    
3559
                // item2가 item1으로 조인
3560
                _placement.PIDJoinRuns(ref item1, ref item2);
3561
                item1.Commit();
3562
                item2.Commit();
3563

    
3564
                string beforeID = string.Empty;
3565
                string afterID = string.Empty;
3566

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

    
3604
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3605
                {
3606
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3607
                    foreach (var line in lines)
3608
                        line.SPPID.ModelItemId = afterID;
3609
                }
3610

    
3611
                ReleaseCOMObjects(modelItem1);
3612
                ReleaseCOMObjects(item1);
3613
                ReleaseCOMObjects(modelItem2);
3614
                ReleaseCOMObjects(item2);
3615
            }
3616
            catch (Exception ex)
3617
            {
3618
                Log.Write("Join Error");
3619
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3620
            }
3621
        }
3622

    
3623
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3624
        {
3625
            bool result = false;
3626
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3627
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3628
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3629

    
3630
            foreach (var item in endBreaks)
3631
            {
3632
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3633
                {
3634
                    result = true;
3635
                    break;
3636
                }
3637
            }
3638

    
3639
            return result;
3640
        }
3641
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3642
        {
3643
            List<string> temp = new List<string>();
3644
            List<LMConnector> connectors = new List<LMConnector>();
3645
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3646
            {
3647
                if (connector.get_ItemStatus() != "Active")
3648
                    continue;
3649

    
3650
                LMModelItem modelItem = connector.ModelItemObject;
3651
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3652
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3653
                    temp.Add(modelItem.Id);
3654

    
3655
                if (temp.Contains(modelItem.Id) &&
3656
                    connOtherSymbol != null &&
3657
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3658
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3659
                    temp.Remove(modelItem.Id);
3660

    
3661

    
3662
                if (temp.Contains(modelItem.Id))
3663
                    connectors.Add(connector);
3664
                ReleaseCOMObjects(connOtherSymbol);
3665
                connOtherSymbol = null;
3666
                ReleaseCOMObjects(modelItem);
3667
                modelItem = null;
3668
            }
3669

    
3670
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3671
            {
3672
                if (connector.get_ItemStatus() != "Active")
3673
                    continue;
3674

    
3675
                LMModelItem modelItem = connector.ModelItemObject;
3676
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3677
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3678
                    temp.Add(modelItem.Id);
3679

    
3680
                if (temp.Contains(modelItem.Id) &&
3681
                    connOtherSymbol != null &&
3682
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3683
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3684
                    temp.Remove(modelItem.Id);
3685

    
3686
                if (temp.Contains(modelItem.Id))
3687
                    connectors.Add(connector);
3688
                ReleaseCOMObjects(connOtherSymbol);
3689
                connOtherSymbol = null;
3690
                ReleaseCOMObjects(modelItem);
3691
                modelItem = null;
3692
            }
3693

    
3694

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

    
3716
            foreach (var connector in connectors)
3717
                ReleaseCOMObjects(connector);
3718
            
3719
            return result;
3720

    
3721

    
3722
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3723
            {
3724
                LMSymbol findResult = null;
3725
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3726
                    findResult = connector.ConnectItem1SymbolObject;
3727
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3728
                    findResult = connector.ConnectItem2SymbolObject;
3729

    
3730
                return findResult;
3731
            }
3732
        }
3733

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

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

    
3774
                ReleaseCOMObjects(modelItem);
3775
            }
3776

    
3777
            return connectorVertices;
3778
        }
3779

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

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

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

    
3890
                    if ((x1 <= connX && x2 >= connX) ||
3891
                        (y1 <= connY && y2 >= connY))
3892
                    {
3893
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3894
                        if (length >= distance)
3895
                        {
3896
                            targetConnector = item.Key;
3897
                            length = distance;
3898
                        }
3899

    
3900
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3901
                        if (length >= distance)
3902
                        {
3903
                            targetConnector = item.Key;
3904
                            length = distance;
3905
                        }
3906
                    }
3907
                }
3908
            }
3909

    
3910
            // 못찾았을때.
3911
            length = double.MaxValue;
3912
            if (targetConnector == null)
3913
            {
3914
                foreach (var item in connectorVertices)
3915
                {
3916
                    List<double[]> points = item.Value;
3917

    
3918
                    foreach (double[] point in points)
3919
                    {
3920
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3921
                        if (length >= distance)
3922
                        {
3923
                            targetConnector = item.Key;
3924
                            length = distance;
3925
                        }
3926
                    }
3927
                }
3928
            }
3929

    
3930
            return targetConnector;
3931
        }
3932

    
3933
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3934
        {
3935
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3936
            if (vertices.Count == 0)
3937
                return null;
3938

    
3939
            double length = double.MaxValue;
3940
            LMConnector targetConnector = null;
3941
            double[] resultPoint = null;
3942
            List<double[]> targetVertices = null;
3943

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

    
3954
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3955
                    if (length >= distance)
3956
                    {
3957
                        targetConnector = item.Key;
3958
                        length = distance;
3959
                        resultPoint = point;
3960
                        targetVertices = item.Value;
3961
                    }
3962
                }
3963
            }
3964

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

    
3974
                    double maxLineX = Math.Max(point1[0], point2[0]);
3975
                    double minLineX = Math.Min(point1[0], point2[0]);
3976
                    double maxLineY = Math.Max(point1[1], point2[1]);
3977
                    double minLineY = Math.Min(point1[1], point2[1]);
3978

    
3979
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3980

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

    
4017
            foreach (var item in vertices)
4018
                if (item.Key != null && item.Key != targetConnector)
4019
                    ReleaseCOMObjects(item.Key);
4020

    
4021
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4022
            {
4023
                double tempResultX = resultPoint[0];
4024
                double tempResultY = resultPoint[1];
4025
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4026

    
4027
                GridSetting gridSetting = GridSetting.GetInstance();
4028

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

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

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

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

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

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

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

    
4188
            x = resultPoint[0];
4189
            y = resultPoint[1];
4190

    
4191
            return targetConnector;
4192
        }
4193

    
4194
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4195
        {
4196
            LMConnector result = null;
4197
            List<LMConnector> connectors = new List<LMConnector>();
4198
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4199

    
4200
            if (modelItem != null)
4201
            {
4202
                foreach (LMRepresentation rep in modelItem.Representations)
4203
                {
4204
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4205
                        connectors.Add(dataSource.GetConnector(rep.Id));
4206
                }
4207

    
4208
                ReleaseCOMObjects(modelItem);
4209
            }
4210

    
4211
            if (connectors.Count == 1)
4212
                result = connectors[0];
4213
            else
4214
                foreach (var item in connectors)
4215
                    ReleaseCOMObjects(item);
4216

    
4217
            return result;
4218
        }
4219

    
4220
        private LMConnector GetLMConnectorFirst(string modelItemID)
4221
        {
4222
            LMConnector result = null;
4223
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4224

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

    
4249
            return result;
4250
        }
4251

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

    
4267
            return result;
4268
        }
4269

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

    
4284
            return result;
4285
        }
4286

    
4287
        private void LineNumberModeling(LineNumber lineNumber)
4288
        {
4289
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4290
            if (line != null)
4291
            {
4292
                double x = 0;
4293
                double y = 0;
4294
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4295

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

    
4305
                    if (_LmLabelPresist != null)
4306
                    {
4307
                        _LmLabelPresist.Commit();
4308
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4309
                        ReleaseCOMObjects(_LmLabelPresist);
4310
                    }
4311
                }
4312

    
4313
                foreach (var item in connectorVertices)
4314
                    ReleaseCOMObjects(item.Key);
4315
            }
4316
        }
4317
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4318
        {
4319
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4320
            if (line == null || line.SPPID.Vertices == null)
4321
                return;
4322

    
4323
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4324
            {
4325
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4326
                if (removeLabel != null)
4327
                {
4328
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4329
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4330

    
4331
                    GridSetting gridSetting = GridSetting.GetInstance();
4332
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4333

    
4334
                    double[] labelRange = null;
4335
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4336
                    List<double[]> vertices = GetConnectorVertices(connector);
4337

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

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

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

    
4381
                        double lineX = (lineStartX + lineEndX) / 2;
4382
                        double lineY = (lineStartY + lineEndY) / 2;
4383
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4384
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4385

    
4386
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4387
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4388
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4389
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4390

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

    
4428
                        if (offsetY != 0 || offsetY != 0)
4429
                        {
4430
                            if (connector.ConnectItem1SymbolObject != null &&
4431
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4432
                            {
4433
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4434

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

    
4448
                                double x1, y1, x2, y2, originX, originY;
4449
                                symbol.Range(out x1, out y1, out x2, out y2);
4450
                                symbol.GetOrigin(out originX, out originY);
4451
                                if (originX < lineNumber.SPPID.SPPID_X)
4452
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4453
                                else
4454
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4455
                            }
4456

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

    
4469
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4470
                        {
4471
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4472
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4473
                        }
4474
                    }
4475

    
4476

    
4477
                    ReleaseCOMObjects(connector);
4478
                    connector = null;
4479
                }
4480

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

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

    
4526
                return 0;
4527
            }
4528

    
4529
            foreach (LineRun run in lineNumber.RUNS)
4530
            {
4531
                foreach (var item in run.RUNITEMS)
4532
                {
4533
                    if (item.GetType() == typeof(Symbol))
4534
                    {
4535
                        Symbol symbol = item as Symbol;
4536
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4537
                        if (_LMSymbol != null)
4538
                        {
4539
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4540

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

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

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

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

    
4671
                ReleaseCOMObjects(_Attributes);
4672
                ReleaseCOMObjects(_LMModelItem);
4673
                ReleaseCOMObjects(_LMSymbol);
4674
            }
4675
        }
4676

    
4677
        /// <summary>
4678
        /// Input SpecBreak Attribute
4679
        /// </summary>
4680
        /// <param name="specBreak"></param>
4681
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4682
        {
4683
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4684
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4685

    
4686
            if (upStreamObj != null &&
4687
                downStreamObj != null)
4688
            {
4689
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4690

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

    
4708
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4709
                                }
4710
                            }
4711
                        }
4712
                    }
4713

    
4714
                    ReleaseCOMObjects(targetLMConnector);
4715
                }
4716
            }
4717

    
4718

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

    
4739
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4740
                    {
4741
                        if (connector.get_ItemStatus() != "Active")
4742
                            continue;
4743

    
4744
                        if (connector.Id != zeroLenthConnector.Id)
4745
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4746
                    }
4747

    
4748
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4749
                    {
4750
                        if (connector.get_ItemStatus() != "Active")
4751
                            continue;
4752

    
4753
                        if (connector.Id != zeroLenthConnector.Id)
4754
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4755
                    }
4756

    
4757
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4758
                    {
4759
                        if (connector.get_ItemStatus() != "Active")
4760
                            continue;
4761

    
4762
                        if (connector.Id != zeroLenthConnector.Id)
4763
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4764
                    }
4765

    
4766
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4767
                    {
4768
                        if (connector.get_ItemStatus() != "Active")
4769
                            continue;
4770

    
4771
                        if (connector.Id != zeroLenthConnector.Id)
4772
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4773
                    }
4774

    
4775
                    ReleaseCOMObjects(zeroLenthConnector);
4776
                    ReleaseCOMObjects(upStreamLMSymbol);
4777
                    ReleaseCOMObjects(downStreamLMSymbol);
4778
                }
4779
                else if (upStreamSymbol != null && downStreamLine != null)
4780
                {
4781
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4782
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4783
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4784

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

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

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

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

    
4803
                    ReleaseCOMObjects(zeroLenthConnector);
4804
                    ReleaseCOMObjects(upStreamLMSymbol);
4805
                }
4806
                else if (upStreamLine != null && downStreamSymbol != null)
4807
                {
4808
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4809
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4810
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4811

    
4812
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4813
                    {
4814
                        if (connector.get_ItemStatus() != "Active")
4815
                            continue;
4816

    
4817
                        if (connector.Id == zeroLenthConnector.Id)
4818
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4819
                    }
4820

    
4821
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4822
                    {
4823
                        if (connector.get_ItemStatus() != "Active")
4824
                            continue;
4825

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

    
4830
                    ReleaseCOMObjects(zeroLenthConnector);
4831
                    ReleaseCOMObjects(downStreamLMSymbol);
4832
                }
4833
            }
4834

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

    
4849
                    _LMModelItem.Commit();
4850
                }
4851
                if (_LMModelItem != null)
4852
                    ReleaseCOMObjects(_LMModelItem);
4853
            }
4854

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

    
4869
                    _LMModelItem.Commit();
4870
                }
4871
                if (_LMModelItem != null)
4872
                    ReleaseCOMObjects(_LMModelItem);
4873
            }
4874
            #endregion
4875
        }
4876

    
4877
        private void InputEndBreakAttribute(EndBreak endBreak)
4878
        {
4879
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4880
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4881

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

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

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

    
4995
                                        loopModelItems = loopModelItems.Distinct().ToList();
4996
                                        if (loopModelItems.Count == 1)
4997
                                        {
4998
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4999
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5000
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5001
                                            modelItem.Commit();
5002
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5003
                                            ZeroLengthModelItem.Commit();
5004

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

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

    
5043
            LMItemNote _LMItemNote = null;
5044
            LMAAttribute _LMAAttribute = null;
5045

    
5046
            double x = 0;
5047
            double y = 0;
5048
            double angle = text.ANGLE;
5049
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5050

    
5051
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5052
            text.SPPID.SPPID_X = x;
5053
            text.SPPID.SPPID_Y = y;
5054

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

    
5070

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

    
5093
                        if (_LMAAttribute != null)
5094
                            ReleaseCOMObjects(_LMAAttribute);
5095
                        if (_LMItemNote != null)
5096
                            ReleaseCOMObjects(_LMItemNote);
5097
                    }
5098

    
5099
                    TextCorrectModeling(text);
5100
                }
5101
            }
5102
            if (_LMSymbol != null)
5103
                ReleaseCOMObjects(_LMSymbol);
5104
        }
5105

    
5106
        private void DefaultTextModeling(string value, double x, double y)
5107
        {
5108
            LMSymbol _LMSymbol = null;
5109

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

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

    
5127
                        if (_LMAAttribute != null)
5128
                            ReleaseCOMObjects(_LMAAttribute);
5129
                        if (_LMItemNote != null)
5130
                            ReleaseCOMObjects(_LMItemNote);
5131
                    }
5132
                }
5133
            }
5134
            if (_LMSymbol != null)
5135
                ReleaseCOMObjects(_LMSymbol);
5136
        }
5137

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

    
5154
                        if (mapping != null)
5155
                        {
5156
                            double x = 0;
5157
                            double y = 0;
5158

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

    
5181
                if (connectedLMConnector != null)
5182
                {
5183
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5184
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5185
                    {
5186
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5187

    
5188
                        if (mapping != null)
5189
                        {
5190
                            double x = 0;
5191
                            double y = 0;
5192
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5193
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5194
                            Array array = new double[] { 0, x, y };
5195

    
5196
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5197
                            if (_LMLabelPersist != null)
5198
                            {
5199
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5200
                                _LMLabelPersist.Commit();
5201
                                ReleaseCOMObjects(_LMLabelPersist);
5202
                            }
5203
                        }
5204
                    }
5205
                }
5206
            }
5207
            if (_LMSymbol != null)
5208
                ReleaseCOMObjects(_LMSymbol);
5209
        }
5210

    
5211
        private void TextCorrectModeling(Text text)
5212
        {
5213
            if (text.SPPID.Range == null)
5214
                return;
5215

    
5216
            bool needRemodeling = false;
5217
            bool loop = true;
5218
            GridSetting gridSetting = GridSetting.GetInstance();
5219
            while (loop)
5220
            {
5221
                loop = false;
5222
                foreach (var overlapText in document.TEXTINFOS)
5223
                {
5224
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5225
                        continue;
5226

    
5227
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5228
                    {
5229
                        double percentX = 0;
5230
                        double percentY = 0;
5231
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5232
                        {
5233
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5234
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5235
                        }
5236
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5237
                        {
5238
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5239
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5240
                        }
5241

    
5242
                        double tempX = 0;
5243
                        double tempY = 0;
5244
                        bool overlapX = false;
5245
                        bool overlapY = false;
5246
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5247
                        if (percentX >= percentY)
5248
                        {
5249
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5250
                            double move = gridSetting.Length * count;
5251
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5252
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5253
                            needRemodeling = true;
5254
                            loop = true;
5255
                        }
5256
                        else
5257
                        {
5258
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5259
                            double move = gridSetting.Length * count;
5260
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5261
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5262
                            needRemodeling = true;
5263
                            loop = true;
5264
                        }
5265
                    }
5266
                }
5267
            }
5268
            
5269

    
5270
            if (needRemodeling)
5271
            {
5272
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5273
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5274
                text.SPPID.RepresentationId = null;
5275

    
5276
                LMItemNote _LMItemNote = null;
5277
                LMAAttribute _LMAAttribute = null;
5278
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5279
                if (_LMSymbol != null)
5280
                {
5281
                    _LMSymbol.Commit();
5282
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5283
                    if (_LMItemNote != null)
5284
                    {
5285
                        _LMItemNote.Commit();
5286
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5287
                        if (_LMAAttribute != null)
5288
                        {
5289
                            _LMAAttribute.set_Value(text.VALUE);
5290
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5291
                            _LMItemNote.Commit();
5292

    
5293
                            ReleaseCOMObjects(_LMAAttribute);
5294
                            ReleaseCOMObjects(_LMItemNote);
5295
                        }
5296
                    }
5297
                }
5298

    
5299
                ReleaseCOMObjects(symbol);
5300
                symbol = null;
5301
                ReleaseCOMObjects(_LMItemNote);
5302
                _LMItemNote = null;
5303
                ReleaseCOMObjects(_LMAAttribute);
5304
                _LMAAttribute = null;
5305
                ReleaseCOMObjects(_LMSymbol);
5306
                _LMSymbol = null;
5307
            }
5308
        }
5309

    
5310
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5311
        {
5312
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5313
            {
5314
                List<Text> allTexts = new List<Text>();
5315
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5316
                LMRepresentation representation = targetLabel.RepresentationObject;
5317
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5318
                if (targetLabel.RepresentationObject != null && symbol != null)
5319
                {
5320
                    double[] symbolRange = null;
5321
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5322
                    if (symbolRange != null)
5323
                    {
5324
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5325
                        {
5326
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5327
                            if (findText != null)
5328
                            {
5329
                                double[] range = null;
5330
                                GetSPPIDSymbolRange(labelPersist, ref range);
5331
                                findText.SPPID.Range = range;
5332
                                allTexts.Add(findText);
5333
                            }
5334

    
5335
                            ReleaseCOMObjects(labelPersist);
5336
                        }
5337

    
5338
                        if (allTexts.Count > 0)
5339
                        {
5340
                            #region Sort Text By Y
5341
                            allTexts.Sort(SortTextByY);
5342
                            int SortTextByY(Text a, Text b)
5343
                            {
5344
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5345
                            }
5346
                            #endregion
5347

    
5348
                            #region 정렬하기전 방향
5349
                            List<Text> left = new List<Text>();
5350
                            List<Text> down = new List<Text>();
5351
                            List<Text> right = new List<Text>();
5352
                            List<Text> up = new List<Text>();
5353
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5354
                            foreach (var loopText in allTexts)
5355
                            {
5356
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5357
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5358
                                double originX = 0;
5359
                                double originY = 0;
5360
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5361
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5362

    
5363
                                if (angle < 45)
5364
                                {
5365
                                    // Text 오른쪽
5366
                                    if (textCenterX > originX)
5367
                                        right.Add(loopText);
5368
                                    // Text 왼쪽
5369
                                    else
5370
                                        left.Add(loopText); 
5371
                                }
5372
                                else
5373
                                {
5374
                                    // Text 아래쪽
5375
                                    if (textCenterY > originY)
5376
                                        down.Add(loopText);
5377
                                    // Text 위쪽
5378
                                    else
5379
                                        up.Add(loopText);
5380
                                }
5381
                            }
5382
                            
5383
                            #endregion
5384

    
5385
                            foreach (var texts in sortTexts)
5386
                            {
5387
                                if (texts.Count == 0 )
5388
                                    continue;
5389
                                
5390
                                #region 첫번째 Text로 기준 맞춤
5391
                                for (int i = 0; i < texts.Count; i++)
5392
                                {
5393
                                    if (i != 0)
5394
                                    {
5395
                                        Text currentText = texts[i];
5396
                                        Text prevText = texts[i - 1];
5397
                                        double minY = prevText.SPPID.Range[1];
5398
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5399
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5400
                                        double _gapX = centerX - centerPrevX;
5401
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5402
                                        MoveText(currentText, _gapX, _gapY);
5403
                                    }
5404
                                }
5405
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5406
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5407
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5408
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5409
                                rangeMinX.Sort();
5410
                                rangeMinY.Sort();
5411
                                rangeMaxX.Sort();
5412
                                rangeMaxY.Sort();
5413
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5414
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5415
                                #endregion
5416
                                #region 정렬
5417
                                Text correctBySymbol = texts[0];
5418
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5419
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5420
                                double originX = 0;
5421
                                double originY = 0;
5422
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5423
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5424
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5425
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5426

    
5427
                                double gapX = 0;
5428
                                double gapY = 0;
5429
                                if (angle < 45)
5430
                                {
5431
                                    // Text 오른쪽
5432
                                    if (textCenterX > originX)
5433
                                    {
5434
                                        gapX = rangeMinX[0] - symbolRange[2];
5435
                                        gapY = allTextCenterY - symbolCenterY;
5436
                                    }
5437
                                    // Text 왼쪽
5438
                                    else
5439
                                    {
5440
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5441
                                        gapY = allTextCenterY - symbolCenterY;
5442
                                    }
5443
                                }
5444
                                else
5445
                                {
5446
                                    // Text 아래쪽
5447
                                    if (textCenterY > originY)
5448
                                    {
5449
                                        gapX = allTextCenterX - symbolCenterX;
5450
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5451
                                    }
5452
                                    // Text 위쪽
5453
                                    else
5454
                                    {
5455
                                        gapX = allTextCenterX - symbolCenterX;
5456
                                        gapY = rangeMinY[0] - symbolRange[3];
5457
                                    }
5458
                                }
5459

    
5460
                                foreach (var item in texts)
5461
                                {
5462
                                    MoveText(item, gapX, gapY);
5463
                                    RemodelingAssociationText(item);
5464
                                }
5465
                                #endregion
5466
                            }
5467
                        }
5468
                    }
5469
                }
5470

    
5471
                void MoveText(Text moveText, double x, double y)
5472
                {
5473
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5474
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5475
                    moveText.SPPID.Range = new double[] {
5476
                        moveText.SPPID.Range[0] - x,
5477
                        moveText.SPPID.Range[1]- y,
5478
                        moveText.SPPID.Range[2]- x,
5479
                        moveText.SPPID.Range[3]- y
5480
                    };
5481
                }
5482

    
5483
                endTexts.AddRange(allTexts);
5484

    
5485
                ReleaseCOMObjects(targetLabel);
5486
                targetLabel = null;
5487
                ReleaseCOMObjects(representation);
5488
                representation = null;
5489
            }
5490
        }
5491

    
5492
        private void RemodelingAssociationText(Text text)
5493
        {
5494
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5495
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5496
            removeLabel.Commit();
5497
            ReleaseCOMObjects(removeLabel);
5498
            removeLabel = null;
5499

    
5500
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5501
            if (owner != null && owner.GetType() == typeof(Symbol))
5502
            {
5503
                Symbol symbol = owner as Symbol;
5504
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5505
                if (_LMSymbol != null)
5506
                {
5507
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5508
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5509
                    {
5510
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5511

    
5512
                        if (mapping != null)
5513
                        {
5514
                            double x = 0;
5515
                            double y = 0;
5516

    
5517
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5518
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5519
                            if (_LMLabelPersist != null)
5520
                            {
5521
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5522
                                _LMLabelPersist.Commit();
5523
                            }
5524
                            ReleaseCOMObjects(_LMLabelPersist);
5525
                            _LMLabelPersist = null;
5526
                        }
5527
                    }
5528
                }
5529
                ReleaseCOMObjects(_LMSymbol);
5530
                _LMSymbol = null;
5531
            }
5532
        }
5533

    
5534
        /// <summary>
5535
        /// Note Modeling
5536
        /// </summary>
5537
        /// <param name="note"></param>
5538
        private void NoteModeling(Note note, List<Note> correctList)
5539
        {
5540
            LMSymbol _LMSymbol = null;
5541
            LMItemNote _LMItemNote = null;
5542
            LMAAttribute _LMAAttribute = null;
5543

    
5544
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5545
            {
5546
                double x = 0;
5547
                double y = 0;
5548

    
5549
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5550
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5551
                note.SPPID.SPPID_X = x;
5552
                note.SPPID.SPPID_Y = y;
5553

    
5554
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5555
                if (_LMSymbol != null)
5556
                {
5557
                    _LMSymbol.Commit();
5558
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5559
                    if (_LMItemNote != null)
5560
                    {
5561
                        _LMItemNote.Commit();
5562
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5563
                        if (_LMAAttribute != null)
5564
                        {
5565
                            _LMAAttribute.set_Value(note.VALUE);
5566
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5567

    
5568
                            double[] range = null;
5569
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5570
                            {
5571
                                double[] temp = null;
5572
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5573
                                if (temp != null)
5574
                                {
5575
                                    if (range == null)
5576
                                        range = temp;
5577
                                    else
5578
                                    {
5579
                                        range = new double[] {
5580
                                            Math.Min(range[0], temp[0]),
5581
                                            Math.Min(range[1], temp[1]),
5582
                                            Math.Max(range[2], temp[2]),
5583
                                            Math.Max(range[3], temp[3])
5584
                                        };
5585
                                    }
5586
                                }
5587
                            }
5588
                            if (range != null)
5589
                                correctList.Add(note);
5590
                            note.SPPID.Range = range;
5591

    
5592

    
5593
                            _LMItemNote.Commit();
5594
                        }
5595
                    }
5596
                }
5597
            }
5598

    
5599
            if (_LMAAttribute != null)
5600
                ReleaseCOMObjects(_LMAAttribute);
5601
            if (_LMItemNote != null)
5602
                ReleaseCOMObjects(_LMItemNote);
5603
            if (_LMSymbol != null)
5604
                ReleaseCOMObjects(_LMSymbol);
5605
        }
5606

    
5607
        private void NoteCorrectModeling(Note note, List<Note> endList)
5608
        {
5609
            bool needRemodeling = false;
5610
            bool loop = true;
5611
            GridSetting gridSetting = GridSetting.GetInstance();
5612
            while (loop)
5613
            {
5614
                loop = false;
5615
                foreach (var overlap in endList)
5616
                {
5617
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5618
                    {
5619
                        double tempX = 0;
5620
                        double tempY = 0;
5621
                        bool overlapX = false;
5622
                        bool overlapY = false;
5623
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5624
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5625
                        if (overlapY && angle >= 45)
5626
                        {
5627
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5628
                            double move = gridSetting.Length * count;
5629
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5630
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5631
                            needRemodeling = true;
5632
                            loop = true;
5633
                        }
5634
                        if (overlapX && angle <= 45)
5635
                        {
5636
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5637
                            double move = gridSetting.Length * count;
5638
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5639
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5640
                            needRemodeling = true;
5641
                            loop = true;
5642
                        }
5643
                    }
5644
                }
5645
            }
5646

    
5647

    
5648
            if (needRemodeling)
5649
            {
5650
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5651
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5652
                note.SPPID.RepresentationId = null;
5653

    
5654
                LMItemNote _LMItemNote = null;
5655
                LMAAttribute _LMAAttribute = null;
5656
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5657
                if (_LMSymbol != null)
5658
                {
5659
                    _LMSymbol.Commit();
5660
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5661
                    if (_LMItemNote != null)
5662
                    {
5663
                        _LMItemNote.Commit();
5664
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5665
                        if (_LMAAttribute != null)
5666
                        {
5667
                            _LMAAttribute.set_Value(note.VALUE);
5668
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5669
                            _LMItemNote.Commit();
5670

    
5671
                            ReleaseCOMObjects(_LMAAttribute);
5672
                            ReleaseCOMObjects(_LMItemNote);
5673
                        }
5674
                    }
5675
                }
5676

    
5677
                ReleaseCOMObjects(symbol);
5678
                symbol = null;
5679
                ReleaseCOMObjects(_LMItemNote);
5680
                _LMItemNote = null;
5681
                ReleaseCOMObjects(_LMAAttribute);
5682
                _LMAAttribute = null;
5683
                ReleaseCOMObjects(_LMSymbol);
5684
                _LMSymbol = null;
5685
            }
5686

    
5687
            endList.Add(note);
5688
        }
5689

    
5690
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5691
        {
5692
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5693
            if (modelItem != null)
5694
            {
5695
                foreach (LMRepresentation rep in modelItem.Representations)
5696
                {
5697
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5698
                    {
5699
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5700
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5701
                        {
5702
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5703
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5704
                            if (modelItemIds.Count == 1)
5705
                            {
5706
                                string joinModelItemId = modelItemIds[0];
5707
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5708
                                if (survivorId != null)
5709
                                    break;
5710
                            }
5711
                        }
5712
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5713
                        {
5714
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5715
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5716
                            if (modelItemIds.Count == 1)
5717
                            {
5718
                                string joinModelItemId = modelItemIds[0];
5719
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5720
                                if (survivorId != null)
5721
                                    break;
5722
                            }
5723
                        }
5724
                    }
5725
                }
5726
            }
5727
        }
5728

    
5729
        /// <summary>
5730
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5731
        /// </summary>
5732
        /// <param name="x"></param>
5733
        /// <param name="y"></param>
5734
        /// <param name="originX"></param>
5735
        /// <param name="originY"></param>
5736
        /// <param name="SPPIDLabelLocation"></param>
5737
        /// <param name="location"></param>
5738
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5739
        {
5740
            if (location == Location.None)
5741
            {
5742
                x = originX;
5743
                y = originY;
5744
            }
5745
            else
5746
            {
5747
                if (location.HasFlag(Location.Center))
5748
                {
5749
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5750
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5751
                }
5752

    
5753
                if (location.HasFlag(Location.Left))
5754
                    x = SPPIDLabelLocation.X1;
5755
                else if (location.HasFlag(Location.Right))
5756
                    x = SPPIDLabelLocation.X2;
5757

    
5758
                if (location.HasFlag(Location.Down))
5759
                    y = SPPIDLabelLocation.Y1;
5760
                else if (location.HasFlag(Location.Up))
5761
                    y = SPPIDLabelLocation.Y2;
5762
            }
5763
        }
5764

    
5765
        /// <summary>
5766
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5767
        /// 1. Angle Valve
5768
        /// 2. 3개로 이루어진 Symbol Group
5769
        /// </summary>
5770
        /// <returns></returns>
5771
        private List<Symbol> GetPrioritySymbol()
5772
        {
5773
            DataTable symbolTable = document.SymbolTable;
5774
            // List에 순서대로 쌓는다.
5775
            List<Symbol> symbols = new List<Symbol>();
5776

    
5777
            // Angle Valve 부터
5778
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5779
            {
5780
                if (!symbols.Contains(symbol))
5781
                {
5782
                    double originX = 0;
5783
                    double originY = 0;
5784

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

    
5789
                    SlopeType slopeType1 = SlopeType.None;
5790
                    SlopeType slopeType2 = SlopeType.None;
5791
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5792
                    {
5793
                        double connectorX = 0;
5794
                        double connectorY = 0;
5795
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5796
                        if (slopeType1 == SlopeType.None)
5797
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5798
                        else
5799
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5800
                    }
5801

    
5802
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5803
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5804
                        symbols.Add(symbol);
5805
                }
5806
            }
5807

    
5808
            List<Symbol> tempSymbols = new List<Symbol>();
5809
            // Conn 갯수 기준
5810
            foreach (var item in document.SYMBOLS)
5811
            {
5812
                if (!symbols.Contains(item))
5813
                    tempSymbols.Add(item);
5814
            }
5815
            tempSymbols.Sort(SortSymbolPriority);
5816
            symbols.AddRange(tempSymbols);
5817

    
5818
            return symbols;
5819
        }
5820

    
5821
        private void SetPriorityLine(List<Line> lines)
5822
        {
5823
            lines.Sort(SortLinePriority);
5824

    
5825
            int SortLinePriority(Line a, Line b)
5826
            {
5827
                // Branch 없는것부터
5828
                int branchRetval = CompareBranchLine(a, b);
5829
                if (branchRetval != 0)
5830
                {
5831
                    return branchRetval;
5832
                }
5833
                else
5834
                {
5835
                    // Symbol 연결 갯수
5836
                    int connSymbolRetval = CompareConnSymbol(a, b);
5837
                    if (connSymbolRetval != 0)
5838
                    {
5839
                        return connSymbolRetval;
5840
                    }
5841
                    else
5842
                    {
5843
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5844
                        int connItemRetval = CompareConnItem(a, b);
5845
                        if (connItemRetval != 0)
5846
                        {
5847
                            return connItemRetval;
5848
                        }
5849
                        else
5850
                        {
5851
                            // ConnectedItem이 없는것
5852
                            int noneConnRetval = CompareNoneConn(a, b);
5853
                            if (noneConnRetval != 0)
5854
                            {
5855
                                return noneConnRetval;
5856
                            }
5857
                            else
5858
                            {
5859

    
5860
                            }
5861
                        }
5862
                    }
5863
                }
5864

    
5865
                return 0;
5866
            }
5867

    
5868
            int CompareNotSegmentLine(Line a, Line b)
5869
            {
5870
                List<Connector> connectorsA = a.CONNECTORS
5871
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5872
                    .ToList();
5873

    
5874
                List<Connector> connectorsB = b.CONNECTORS
5875
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5876
                    .ToList();
5877

    
5878
                // 오름차순
5879
                return connectorsB.Count.CompareTo(connectorsA.Count);
5880
            }
5881

    
5882
            int CompareConnSymbol(Line a, Line b)
5883
            {
5884
                List<Connector> connectorsA = a.CONNECTORS
5885
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5886
                    .ToList();
5887

    
5888
                List<Connector> connectorsB = b.CONNECTORS
5889
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5890
                    .ToList();
5891

    
5892
                // 오름차순
5893
                return connectorsB.Count.CompareTo(connectorsA.Count);
5894
            }
5895

    
5896
            int CompareConnItem(Line a, Line b)
5897
            {
5898
                List<Connector> connectorsA = a.CONNECTORS
5899
                    .Where(conn => conn.ConnectedObject != null && 
5900
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5901
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5902
                    .ToList();
5903

    
5904
                List<Connector> connectorsB = b.CONNECTORS
5905
                    .Where(conn => conn.ConnectedObject != null &&
5906
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5907
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5908
                    .ToList();
5909

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

    
5914
            int CompareBranchLine(Line a, Line b)
5915
            {
5916
                List<Connector> connectorsA = a.CONNECTORS
5917
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5918
                    .ToList();
5919
                List<Connector> connectorsB = b.CONNECTORS
5920
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5921
                    .ToList();
5922

    
5923
                // 내림차순
5924
                return connectorsA.Count.CompareTo(connectorsB.Count);
5925
            }
5926

    
5927
            int CompareNoneConn(Line a, Line b)
5928
            {
5929
                List<Connector> connectorsA = a.CONNECTORS
5930
                    .Where(conn => conn.ConnectedObject == null)
5931
                    .ToList();
5932

    
5933
                List<Connector> connectorsB = b.CONNECTORS
5934
                    .Where(conn => conn.ConnectedObject == null)
5935
                    .ToList();
5936

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

    
5942
        private void SortText(List<Text> texts)
5943
        {
5944
            texts.Sort(Sort);
5945

    
5946
            int Sort(Text a, Text b)
5947
            {
5948
                int yRetval = CompareY(a, b);
5949
                if (yRetval != 0)
5950
                {
5951
                    return yRetval;
5952
                }
5953
                else
5954
                {
5955
                    return CompareX(a, b);
5956
                }
5957
            }
5958

    
5959
            int CompareY(Text a, Text b)
5960
            {
5961
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5962
            }
5963

    
5964
            int CompareX(Text a, Text b)
5965
            {
5966
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5967
            }
5968
        }
5969
        private void SortNote(List<Note> notes)
5970
        {
5971
            notes.Sort(Sort);
5972

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

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

    
5991
            int CompareX(Note a, Note b)
5992
            {
5993
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5994
            }
5995
        }
5996

    
5997
        private void SortBranchLines()
5998
        {
5999
            BranchLines.Sort(SortBranchLine);
6000
            int SortBranchLine(Line a, Line b)
6001
            {
6002
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6003
                 x.ConnectedObject.GetType() == typeof(Line) &&
6004
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6005
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6006

    
6007
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6008
                 x.ConnectedObject.GetType() == typeof(Line) &&
6009
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6010
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6011

    
6012
                // 내림차순
6013
                return countA.CompareTo(countB);
6014
            }
6015
        }
6016

    
6017
        private static int SortSymbolPriority(Symbol a, Symbol b)
6018
        {
6019
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6020
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6021
            int retval = countB.CompareTo(countA);
6022
            if (retval != 0)
6023
                return retval;
6024
            else
6025
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6026
        }
6027

    
6028
        private string GetSPPIDFileName(LMModelItem modelItem)
6029
        {
6030
            string symbolPath = null;
6031
            foreach (LMRepresentation rep in modelItem.Representations)
6032
            {
6033
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6034
                {
6035
                    symbolPath = rep.get_FileName();
6036
                    break;
6037
                }
6038
            }
6039
            return symbolPath;
6040
        }
6041

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

    
6058
        /// <summary>
6059
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6060
        /// </summary>
6061
        /// <param name="graphicOID"></param>
6062
        /// <param name="milliseconds"></param>
6063
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6064
        {
6065
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6066
            {
6067
                double minX = 0;
6068
                double minY = 0;
6069
                double maxX = 0;
6070
                double maxY = 0;
6071
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6072
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6073

    
6074
                Thread.Sleep(milliseconds);
6075
            }
6076
        }
6077

    
6078
        /// <summary>
6079
        /// ComObject를 Release
6080
        /// </summary>
6081
        /// <param name="objVars"></param>
6082
        public void ReleaseCOMObjects(params object[] objVars)
6083
        {
6084
            if (objVars != null)
6085
            {
6086
                int intNewRefCount = 0;
6087
                foreach (object obj in objVars)
6088
                {
6089
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6090
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6091
                }
6092
            }
6093
        }
6094

    
6095
        /// IDisposable 구현
6096
        ~AutoModeling()
6097
        {
6098
            this.Dispose(false);
6099
        }
6100

    
6101
        private bool disposed;
6102
        public void Dispose()
6103
        {
6104
            this.Dispose(true);
6105
            GC.SuppressFinalize(this);
6106
        }
6107

    
6108
        protected virtual void Dispose(bool disposing)
6109
        {
6110
            if (this.disposed) return;
6111
            if (disposing)
6112
            {
6113
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6114
            }
6115
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6116
            this.disposed = true;
6117
        }
6118
    }
6119
}
클립보드 이미지 추가 (최대 크기: 500 MB)