프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 617b1abc

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

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

    
48
        public string DocumentLabelText { get; set; }
49

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

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

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

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

    
80
                }
81
            }
82
        }
83

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1088
                        drawingAttributeDT.Dispose();
1089
                    }
1090

    
1091
                    ReleaseCOMObjects(drawing);
1092
                }
1093

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

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

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

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

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

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

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

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

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

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

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

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

    
1235
            LMSymbol _LMSymbol = null;
1236

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

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

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

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

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

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

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

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

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

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

    
1302

    
1303
                }
1304

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

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

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

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

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

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

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

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

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

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

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

    
1446
            return info;
1447
        }
1448

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

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

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

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

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

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

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

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

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

    
1553
            ReleaseCOMObjects(_TargetItem);
1554
        }
1555

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

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

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

    
1598
            ReleaseCOMObjects(_TargetItem);
1599
        }
1600

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

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

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

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

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

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

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

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

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

    
1747
            range = tempRange;
1748
        }
1749

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

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

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

    
1784
                ReleaseCOMObjects(_ChildSymbol);
1785
            }
1786
        }
1787

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

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

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

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

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

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

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

    
1881
                                        if (result)
1882
                                            break;
1883
                                    }
1884

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2007
            ReleaseCOMObjects(_LMSymbol);
2008
        }
2009

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2279

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

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

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

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

    
2373
                            placeRunInputs.AddPoint(x, y);
2374

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

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

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

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

    
2411
                    FlowMarkModeling(groupLine);
2412

    
2413
                    ReleaseCOMObjects(_lMConnector);
2414

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

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

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

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

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

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

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

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

    
2529
            return _lMConnector;
2530
        }
2531

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

    
2560
                ReleaseCOMObjects(modelItem);
2561
            }
2562
        }
2563

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

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

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

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

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

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

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

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

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

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

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

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

    
2723
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
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_X = x;
2730
                if (line.SlopeType == SlopeType.VERTICAL)
2731
                    line.SPPID.END_X = x;
2732
            }
2733
            else
2734
            {
2735
                line.SPPID.END_X = x;
2736
                if (line.SlopeType == SlopeType.VERTICAL)
2737
                    line.SPPID.START_X = x;
2738
            }
2739
        }
2740

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2924
            ReleaseCOMObjects(modelItem);
2925
        }
2926

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

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

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

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

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

    
2990
                    break;
2991
                }
2992
            }
2993

    
2994
            return _LMSymbol;
2995
        }
2996

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

    
3013
            return null;
3014
        }
3015

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3169
            return newConnector;
3170
        }
3171

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

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

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

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

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

    
3217
                                ReleaseCOMObjects(_LmLabelPersist);
3218
                            }
3219

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3359
            }
3360

    
3361
            return targetConnector;
3362
        }
3363

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

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

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

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

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

    
3458
            return result;
3459
        }
3460

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

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

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

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

    
3507
                    ReleaseCOMObjects(_LMConnector);
3508
                }
3509
            }
3510

    
3511

    
3512
            return result;
3513
        }
3514

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3702

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

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

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

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

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

    
3735

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

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

    
3762

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

    
3771
                return findResult;
3772
            }
3773
        }
3774

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

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

    
3815
                ReleaseCOMObjects(modelItem);
3816
            }
3817

    
3818
            return connectorVertices;
3819
        }
3820

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

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

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

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

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

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

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

    
3971
            return targetConnector;
3972
        }
3973

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

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

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

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

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

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

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

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

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

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

    
4068
                GridSetting gridSetting = GridSetting.GetInstance();
4069

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

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

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

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

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

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

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

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

    
4232
            return targetConnector;
4233
        }
4234

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

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

    
4249
                ReleaseCOMObjects(modelItem);
4250
            }
4251

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

    
4258
            return result;
4259
        }
4260

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

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

    
4290
            return result;
4291
        }
4292

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

    
4308
            return result;
4309
        }
4310

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

    
4325
            return result;
4326
        }
4327

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4517

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

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

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

    
4567
                return 0;
4568
            }
4569

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

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

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

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

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

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

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

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

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

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

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

    
4781
                    ReleaseCOMObjects(targetLMConnector);
4782
                }
4783
            }
4784

    
4785

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5137

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5414
                            ReleaseCOMObjects(labelPersist);
5415
                        }
5416

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

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

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

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

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

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

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

    
5562
                endTexts.AddRange(allTexts);
5563

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

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

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

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

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

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

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

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

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

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

    
5671

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

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

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

    
5726

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

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

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

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

    
5766
            endList.Add(note);
5767
        }
5768

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

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

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

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

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

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

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

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

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

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

    
5897
            return symbols;
5898
        }
5899

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

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

    
5939
                            }
5940
                        }
5941
                    }
5942
                }
5943

    
5944
                return 0;
5945
            }
5946

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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