프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 9f04c985

이력 | 보기 | 이력해설 | 다운로드 (294 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
            for (int i = 0; i < document.Equipments.Count; i++)
226
            {
227
                Equipment item = document.Equipments[i];
228
                try
229
                {
230
                    if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
231
                        continue;
232
                    EquipmentModeling(item);
233
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
234
                    if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
235
                        i = -1;
236
                }
237
                catch (Exception ex)
238
                {
239
                    Log.Write("Error in EquipmentModeling");
240
                    Log.Write("UID : " + item.UID);
241
                    Log.Write(ex.Message);
242
                    Log.Write(ex.StackTrace);
243
                }
244
            }
245
        }
246
        private void RunSymbolModeling()
247
        {
248
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
249
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
250
            prioritySymbols = GetPrioritySymbol();
251
            foreach (var item in prioritySymbols)
252
            {
253
                try
254
                {
255
                    if (document.VentDrainSymbol.Contains(item))
256
                        continue;
257
                    SymbolModelingBySymbol(item);
258
                }
259
                catch (Exception ex)
260
                {
261
                    Log.Write("Error in SymbolModelingByPriority");
262
                    Log.Write("UID : " + item.UID);
263
                    Log.Write(ex.Message);
264
                    Log.Write(ex.StackTrace);
265
                }
266
            }
267
        }
268
        private void RunLineModeling()
269
        {
270
            List<Line> AllLine = document.LINES.ToList();
271
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
272
            !SPPIDUtil.IsBranchedLine(document, x));
273
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
274

    
275
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
276
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
277

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

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

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

    
355
                        GridSetting grid = GridSetting.GetInstance();
356
                        int count = grid.DrainValveCellCount;
357
                        double length = grid.Length;
358

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

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

    
416
                                    // 제거
417
                                    RemoveSymbol(connSymbol);
418
                                    RemoveLine(item);
419

    
420
                                    // 재생성
421
                                    SymbolModelingBySymbol(connSymbol);
422
                                    NewLineModeling(item, true);
423
                                }
424
                            }
425

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

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

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

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

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

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

    
601
                LMRelationships relationships = new LMRelationships();
602
                relationships.Collect(dataSource, Filter: filter);
603

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

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

    
763
                    }
764
                }
765
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
766
            }
767

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

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

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

    
989
        }
990
        private void RunCorrectAssociationText()
991
        {
992
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
993
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
994
            List<Text> endTexts = new List<Text>();
995
            foreach (var item in document.TEXTINFOS)
996
            {
997
                try
998
                {
999
                    if (item.ASSOCIATION && !endTexts.Contains(item))
1000
                        AssociationTextCorrectModeling(item, endTexts);
1001
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1002
                }
1003
                catch (Exception ex)
1004
                {
1005
                    Log.Write("Error in RunCorrectAssociationText");
1006
                    Log.Write("UID : " + item.UID);
1007
                    Log.Write(ex.Message);
1008
                    Log.Write(ex.StackTrace);
1009
                }
1010
                
1011
            }
1012

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

    
1069
                //current LMDrawing 가져오기
1070
                LMAFilter filter = new LMAFilter();
1071
                LMACriterion criterion = new LMACriterion();
1072
                filter.ItemType = "Drawing";
1073
                criterion.SourceAttributeName = "Name";
1074
                criterion.Operator = "=";
1075
                criterion.set_ValueAttribute(drawingName);
1076
                filter.get_Criteria().Add(criterion);
1077

    
1078
                LMDrawings drawings = new LMDrawings();
1079
                drawings.Collect(dataSource, Filter: filter);
1080

    
1081
                // Input Drawing Attribute
1082
                LMDrawing drawing = ((dynamic)drawings).Nth(1);
1083
                if (drawing != null)
1084
                {
1085
                    using (DataTable drawingAttributeDT = Project_DB.SelectDrawingProjectAttribute())
1086
                    {
1087
                        foreach (DataRow row in drawingAttributeDT.Rows)
1088
                        {
1089
                            string mappingName = DBNull.Value.Equals(row["SPPID_ATTRIBUTE"]) ? string.Empty : row["SPPID_ATTRIBUTE"].ToString();
1090
                            if (!string.IsNullOrEmpty(mappingName))
1091
                            {
1092
                                string uid = row["UID"].ToString();
1093
                                string name = row["NAME"].ToString();
1094
                                Text text = document.TEXTINFOS.Find(x => x.AREA == uid);
1095
                                if (text != null)
1096
                                {
1097
                                    string value = text.VALUE;
1098
                                    LMAAttribute attribute = drawing.Attributes[mappingName];
1099
                                    if (attribute != null)
1100
                                        attribute.set_Value(value);
1101
                                    ReleaseCOMObjects(attribute);
1102
                                    document.TEXTINFOS.Remove(text);
1103
                                }
1104
                            }
1105
                        }
1106

    
1107
                        drawingAttributeDT.Dispose();
1108
                    }
1109

    
1110
                    ReleaseCOMObjects(drawing);
1111
                }
1112

    
1113
                drawingID = ((dynamic)drawings).Nth(1).Id;
1114
                ReleaseCOMObjects(filter);
1115
                ReleaseCOMObjects(criterion);
1116
                ReleaseCOMObjects(drawings);
1117
                filter = null;
1118
                criterion = null;
1119
                drawings = null;
1120
            }
1121
            else
1122
                Log.Write("Fail Create Drawing");
1123

    
1124
            if (newDrawing != null)
1125
            {
1126
                SetBorderFile();
1127
                return true;
1128
            }
1129
            else
1130
                return false;
1131
        }
1132

    
1133
        private void SetBorderFile()
1134
        {
1135
            ETCSetting setting = ETCSetting.GetInstance();
1136

    
1137
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1138
            {
1139
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1140
                {
1141
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1142
                    {
1143
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1144
                        smartFrame.Update();
1145
                    }
1146
                        
1147
                }
1148
            }
1149
        }
1150

    
1151
        /// <summary>
1152
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1153
        /// </summary>
1154
        /// <param name="drawingName"></param>
1155
        /// <param name="drawingNumber"></param>
1156
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1157
        {
1158
            LMDrawings drawings = new LMDrawings();
1159
            drawings.Collect(dataSource);
1160

    
1161
            List<string> drawingNameList = new List<string>();
1162
            List<string> drawingNumberList = new List<string>();
1163

    
1164
            foreach (LMDrawing item in drawings)
1165
            {
1166
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1167
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1168
            }
1169

    
1170
            int nameLength = drawingName.Length;
1171
            while (drawingNameList.Contains(drawingName))
1172
            {
1173
                if (nameLength == drawingName.Length)
1174
                    drawingName += "-1";
1175
                else
1176
                {
1177
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1178
                    drawingName = drawingName.Substring(0, nameLength + 1);
1179
                    drawingName += ++index;
1180
                }
1181
            }
1182

    
1183
            int numberLength = drawingNumber.Length;
1184
            while (drawingNameList.Contains(drawingNumber))
1185
            {
1186
                if (numberLength == drawingNumber.Length)
1187
                    drawingNumber += "-1";
1188
                else
1189
                {
1190
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1191
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1192
                    drawingNumber += ++index;
1193
                }
1194
            }
1195
            ReleaseCOMObjects(drawings);
1196
            drawings = null;
1197
        }
1198

    
1199
        /// <summary>
1200
        /// 도면 크기 구하는 메서드
1201
        /// </summary>
1202
        /// <returns></returns>
1203
        private bool DocumentCoordinateCorrection()
1204
        {
1205
            //if (radApp.ActiveDocument.ActiveSheet.SmartFrames2d.Count > 0)
1206
            //{
1207
            //    double x = 0;
1208
            //    double y = 0;
1209
            //    foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1210
            //    {
1211
            //        x = Math.Max(smartFrame.CropRight, x);
1212
            //        y = Math.Max(smartFrame.CropTop, y);
1213
            //    }
1214
            //    document.SetSPPIDLocation(x, y);
1215
            //    document.CoordinateCorrection();
1216
            //    return true;
1217
            //}
1218
            //else
1219
            //{
1220
            //    Log.Write("Need Border!");
1221
            //    return false;
1222
            //}
1223

    
1224
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1225
            {
1226
                Log.Write("Setting Drawing X, Drawing Y");
1227
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1228
                Log.Write("Start coordinate correction");
1229
                document.CoordinateCorrection();
1230
                return true;
1231
            }
1232
            else
1233
            {
1234
                Log.Write("Need Drawing X, Y");
1235
                return false;
1236
            }
1237
        }
1238

    
1239
        /// <summary>
1240
        /// 심볼을 실제로 Modeling 메서드
1241
        /// </summary>
1242
        /// <param name="symbol">생성할 심볼</param>
1243
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1244
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1245
        {
1246
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1247
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1248
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1249
                return;
1250
            // 이미 모델링 됐을 경우
1251
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1252
                return;
1253

    
1254
            LMSymbol _LMSymbol = null;
1255

    
1256
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1257
            double x = symbol.SPPID.ORIGINAL_X;
1258
            double y = symbol.SPPID.ORIGINAL_Y;
1259
            int mirror = 0;
1260
            double angle = symbol.ANGLE;
1261

    
1262
            // OPC 일경우 180도 일때 Mirror
1263
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1264
                mirror = 1;
1265

    
1266
            // Mirror 계산
1267
            if (symbol.FLIP == 1)
1268
            {
1269
                mirror = 1;
1270
                if (angle == Math.PI || angle == 0)
1271
                    angle += Math.PI;
1272
            }
1273

    
1274
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1275
            {
1276
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1277
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1278
                if (connector != null)
1279
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1280

    
1281
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1282
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1283
                if (temp != null)
1284
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1285
                ReleaseCOMObjects(temp);
1286
                temp = null;
1287

    
1288
                if (_LMSymbol != null && _TargetItem != null)
1289
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1290

    
1291
                ReleaseCOMObjects(_TargetItem);
1292
            }
1293
            else
1294
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1295

    
1296
            if (_LMSymbol != null)
1297
            {
1298
                _LMSymbol.Commit();
1299

    
1300
                // ConnCheck
1301
                List<string> ids = new List<string>();
1302
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1303
                {
1304
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1305
                        ids.Add(item.Id);
1306
                    ReleaseCOMObjects(item);
1307
                }
1308
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1309
                {
1310
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1311
                        ids.Add(item.Id);
1312
                    ReleaseCOMObjects(item);
1313
                }
1314

    
1315
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1316
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1317
                {
1318
                    double currentX = _LMSymbol.get_XCoordinate();
1319
                    double currentY = _LMSymbol.get_YCoordinate();
1320

    
1321

    
1322
                }
1323

    
1324
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1325
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1326
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1327

    
1328
                foreach (var item in symbol.ChildSymbols)
1329
                    CreateChildSymbol(item, _LMSymbol, symbol);
1330

    
1331
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1332
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1333

    
1334
                double[] range = null;
1335
                GetSPPIDSymbolRange(symbol, ref range);
1336
                symbol.SPPID.SPPID_Min_X = range[0];
1337
                symbol.SPPID.SPPID_Min_Y = range[1];
1338
                symbol.SPPID.SPPID_Max_X = range[2];
1339
                symbol.SPPID.SPPID_Max_Y = range[3];
1340

    
1341
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1342
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1343
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1344
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1345

    
1346
                ReleaseCOMObjects(_LMSymbol);
1347
            }
1348
        }
1349
        /// <summary>
1350
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1351
        /// Signal Point는 고려하지 않음
1352
        /// </summary>
1353
        /// <param name="symbol"></param>
1354
        /// <param name="_TargetItem"></param>
1355
        /// <param name="targetX"></param>
1356
        /// <param name="targetY"></param>
1357
        /// <returns></returns>
1358
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1359
        {
1360
            LMConnector tempConnector = null;
1361

    
1362
            List<Symbol> group = new List<Symbol>();
1363
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1364
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1365
            {
1366
                List<Connector> connectors = new List<Connector>();
1367
                foreach (var item in group)
1368
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1369
                /// Primary or Secondary Type Line만 고려
1370
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1371
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1372
                if (_connector != null)
1373
                {
1374
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1375
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1376
                    /// PipingPoint가 2개 이상만
1377
                    if (pointInfos.Count >= 2)
1378
                    {
1379
                        double lineX = 0;
1380
                        double lineY = 0;
1381
                        double length = 0;
1382
                        foreach (var item in pointInfos)
1383
                        {
1384
                            double tempX = item[1];
1385
                            double tempY = item[2];
1386

    
1387
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1388
                            if (calcDistance > length)
1389
                            {
1390
                                lineX = tempX;
1391
                                lineY = tempY;
1392
                            }
1393
                        }
1394

    
1395
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1396
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1397
                        placeRunInputs.AddPoint(-1, -1);
1398
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1399
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1400
                        if (tempConnector != null)
1401
                            tempConnector.Commit();
1402
                        ReleaseCOMObjects(_LMAItem);
1403
                        _LMAItem = null;
1404
                        ReleaseCOMObjects(placeRunInputs);
1405
                        placeRunInputs = null;
1406
                    }
1407
                }
1408
            }
1409

    
1410
            return tempConnector;
1411
        }
1412
        /// <summary>
1413
        /// Symbol의 PipingPoints를 구함
1414
        /// SignalPoint는 고려하지 않음
1415
        /// </summary>
1416
        /// <param name="symbol"></param>
1417
        /// <returns></returns>
1418
        private List<double[]> getPipingPoints(LMSymbol symbol)
1419
        {
1420
            LMModelItem modelItem = symbol.ModelItemObject;
1421
            LMPipingPoints pipingPoints = null;
1422
            if (modelItem.get_ItemTypeName() == "PipingComp")
1423
            {
1424
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1425
                pipingPoints = pipingComp.PipingPoints;
1426
                ReleaseCOMObjects(pipingComp);
1427
                pipingComp = null;
1428
            }
1429
            else if (modelItem.get_ItemTypeName() == "Instrument")
1430
            {
1431
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1432
                pipingPoints = instrument.PipingPoints;
1433
                ReleaseCOMObjects(instrument);
1434
                instrument = null;
1435
            }
1436
            else
1437
                Log.Write("다른 Type");
1438

    
1439
            List<double[]> info = new List<double[]>();
1440
            if (pipingPoints != null)
1441
            {
1442
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1443
                {
1444
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1445
                    {
1446
                        if (attribute.Name == "PipingPointNumber")
1447
                        {
1448
                            int index = Convert.ToInt32(attribute.get_Value());
1449
                            if (info.Find(loopX => loopX[0] == index) == null)
1450
                            {
1451
                                double x = 0;
1452
                                double y = 0;
1453
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1454
                                    info.Add(new double[] { index, x, y });
1455
                            }
1456
                        }
1457
                    }
1458
                }
1459
            }
1460
            ReleaseCOMObjects(modelItem);
1461
            modelItem = null;
1462
            ReleaseCOMObjects(pipingPoints);
1463
            pipingPoints = null;
1464

    
1465
            return info;
1466
        }
1467

    
1468
        private void RemoveSymbol(Symbol symbol)
1469
        {
1470
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1471
            {
1472
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1473
                if (_LMSymbol != null)
1474
                {
1475
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1476
                    ReleaseCOMObjects(_LMSymbol);
1477
                }
1478
            }
1479

    
1480
            symbol.SPPID.RepresentationId = string.Empty;
1481
            symbol.SPPID.ModelItemID = string.Empty;
1482
            symbol.SPPID.SPPID_X = double.NaN;
1483
            symbol.SPPID.SPPID_Y = double.NaN;
1484
            symbol.SPPID.SPPID_Min_X = double.NaN;
1485
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1486
            symbol.SPPID.SPPID_Max_X = double.NaN;
1487
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1488
        }
1489

    
1490
        private void RemoveSymbol(List<Symbol> symbols)
1491
        {
1492
            foreach (var symbol in symbols)
1493
            {
1494
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1495
                {
1496
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1497
                    if (_LMSymbol != null)
1498
                    {
1499
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1500
                        ReleaseCOMObjects(_LMSymbol);
1501
                    }
1502
                }
1503

    
1504
                symbol.SPPID.RepresentationId = string.Empty;
1505
                symbol.SPPID.ModelItemID = string.Empty;
1506
                symbol.SPPID.SPPID_X = double.NaN;
1507
                symbol.SPPID.SPPID_Y = double.NaN;
1508
                symbol.SPPID.SPPID_Min_X = double.NaN;
1509
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1510
                symbol.SPPID.SPPID_Max_X = double.NaN;
1511
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1512
            }
1513
        }
1514

    
1515
        /// <summary>
1516
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1517
        /// </summary>
1518
        /// <param name="targetConnector"></param>
1519
        /// <param name="targetSymbol"></param>
1520
        /// <param name="x"></param>
1521
        /// <param name="y"></param>
1522
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1523
        {
1524
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1525

    
1526
            double[] range = null;
1527
            List<double[]> points = new List<double[]>();
1528
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1529
            double x1 = range[0];
1530
            double y1 = range[1];
1531
            double x2 = range[2];
1532
            double y2 = range[3];
1533

    
1534
            // Origin 기준 Connector의 위치차이
1535
            double sceneX = 0;
1536
            double sceneY = 0;
1537
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1538
            double originX = 0;
1539
            double originY = 0;
1540
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1541
            double gapX = originX - sceneX;
1542
            double gapY = originY - sceneY;
1543

    
1544
            // SPPID Symbol과 ID2 심볼의 크기 차이
1545
            double sizeWidth = 0;
1546
            double sizeHeight = 0;
1547
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1548
            if (sizeWidth == 0 || sizeHeight == 0)
1549
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1550

    
1551
            double percentX = (x2 - x1) / sizeWidth;
1552
            double percentY = (y2 - y1) / sizeHeight;
1553

    
1554
            double SPPIDgapX = gapX * percentX;
1555
            double SPPIDgapY = gapY * percentY;
1556

    
1557
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1558
            double distance = double.MaxValue;
1559
            double[] resultPoint;
1560
            foreach (var point in points)
1561
            {
1562
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1563
                if (distance > result)
1564
                {
1565
                    distance = result;
1566
                    resultPoint = point;
1567
                    x = point[0];
1568
                    y = point[1];
1569
                }
1570
            }
1571

    
1572
            ReleaseCOMObjects(_TargetItem);
1573
        }
1574

    
1575
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1576
        {
1577
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1578
            if (index == 0)
1579
            {
1580
                x = targetLine.SPPID.START_X;
1581
                y = targetLine.SPPID.START_Y;
1582
            }
1583
            else
1584
            {
1585
                x = targetLine.SPPID.END_X;
1586
                y = targetLine.SPPID.END_Y;
1587
            }
1588
        }
1589

    
1590
        /// <summary>
1591
        /// SPPID Symbol의 Range를 구한다.
1592
        /// </summary>
1593
        /// <param name="symbol"></param>
1594
        /// <param name="range"></param>
1595
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1596
        {
1597
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1598
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1599
            double x1 = 0;
1600
            double y1 = 0;
1601
            double x2 = 0;
1602
            double y2 = 0;
1603
            symbol2d.Range(out x1, out y1, out x2, out y2);
1604
            range = new double[] { x1, y1, x2, y2 };
1605
            
1606
            for (int i = 1; i < 30; i++)
1607
            {
1608
                double connX = 0;
1609
                double connY = 0;
1610
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1611
                    points.Add(new double[] { connX, connY });
1612
            }
1613

    
1614
            foreach (var childSymbol in symbol.ChildSymbols)
1615
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1616

    
1617
            ReleaseCOMObjects(_TargetItem);
1618
        }
1619

    
1620
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1621
        {
1622
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1623
            if (_TargetItem != null)
1624
            {
1625
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1626
                double x1 = 0;
1627
                double y1 = 0;
1628
                double x2 = 0;
1629
                double y2 = 0;
1630
                if (!bForGraphic)
1631
                {
1632
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1633
                    range = new double[] { x1, y1, x2, y2 };
1634
                }
1635
                else
1636
                {
1637
                    x1 = double.MaxValue;
1638
                    y1 = double.MaxValue;
1639
                    x2 = double.MinValue;
1640
                    y2 = double.MinValue;
1641
                    range = new double[] { x1, y1, x2, y2 };
1642

    
1643
                    foreach (var item in symbol2d.DrawingObjects)
1644
                    {
1645
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1646
                        {
1647
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1648
                            if (rangeObject.Layer == "Default")
1649
                            {
1650
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1651
                                range = new double[] {
1652
                                Math.Min(x1, range[0]),
1653
                                Math.Min(y1, range[1]),
1654
                                Math.Max(x2, range[2]),
1655
                                Math.Max(y2, range[3])
1656
                            };
1657
                            }
1658
                        }
1659
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1660
                        {
1661
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1662
                            if (rangeObject.Layer == "Default")
1663
                            {
1664
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1665
                                range = new double[] {
1666
                                Math.Min(x1, range[0]),
1667
                                Math.Min(y1, range[1]),
1668
                                Math.Max(x2, range[2]),
1669
                                Math.Max(y2, range[3])
1670
                            };
1671
                            }
1672
                        }
1673
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1674
                        {
1675
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1676
                            if (rangeObject.Layer == "Default")
1677
                            {
1678
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1679
                                range = new double[] {
1680
                                Math.Min(x1, range[0]),
1681
                                Math.Min(y1, range[1]),
1682
                                Math.Max(x2, range[2]),
1683
                                Math.Max(y2, range[3])
1684
                            };
1685
                            }
1686
                        }
1687
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1688
                        {
1689
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1690
                            if (rangeObject.Layer == "Default")
1691
                            {
1692
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1693
                                range = new double[] {
1694
                                Math.Min(x1, range[0]),
1695
                                Math.Min(y1, range[1]),
1696
                                Math.Max(x2, range[2]),
1697
                                Math.Max(y2, range[3])
1698
                            };
1699
                            }
1700
                        }
1701
                    }
1702
                }
1703

    
1704
                if (!bOnlySymbol)
1705
                {
1706
                    foreach (var childSymbol in symbol.ChildSymbols)
1707
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1708
                }
1709
                ReleaseCOMObjects(_TargetItem);
1710
            }
1711
        }
1712

    
1713
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1714
        {
1715
            if (labelPersist != null)
1716
            {
1717
                double x1 = double.MaxValue;
1718
                double y1 = double.MaxValue;
1719
                double x2 = double.MinValue;
1720
                double y2 = double.MinValue;
1721
                range = new double[] { x1, y1, x2, y2 };
1722

    
1723
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1724
                foreach (var item in dependency.DrawingObjects)
1725
                {
1726
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1727
                    if (textBox != null)
1728
                    {
1729
                        if (dependency != null)
1730
                        {
1731
                            double tempX1;
1732
                            double tempY1;
1733
                            double tempX2;
1734
                            double tempY2;
1735
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1736
                            x1 = Math.Min(x1, tempX1);
1737
                            y1 = Math.Min(y1, tempY1);
1738
                            x2 = Math.Max(x2, tempX2);
1739
                            y2 = Math.Max(y2, tempY2);
1740

    
1741
                            range = new double[] { x1, y1, x2, y2 };
1742
                        }
1743
                    }
1744
                }
1745
                
1746
            }
1747
        }
1748

    
1749
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1750
        {
1751
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1752
            foreach (var symbol in symbols)
1753
            {
1754
                double[] symbolRange = null;
1755
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
1756

    
1757
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
1758
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
1759
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
1760
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
1761

    
1762
                foreach (var childSymbol in symbol.ChildSymbols)
1763
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1764
            }
1765

    
1766
            range = tempRange;
1767
        }
1768

    
1769
        /// <summary>
1770
        /// Child Modeling 된 Symbol의 Range를 구한다.
1771
        /// </summary>
1772
        /// <param name="childSymbol"></param>
1773
        /// <param name="range"></param>
1774
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1775
        {
1776
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1777
            if (_ChildSymbol != null)
1778
            {
1779
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1780
                double x1 = 0;
1781
                double y1 = 0;
1782
                double x2 = 0;
1783
                double y2 = 0;
1784
                symbol2d.Range(out x1, out y1, out x2, out y2);
1785
                range[0] = Math.Min(range[0], x1);
1786
                range[1] = Math.Min(range[1], y1);
1787
                range[2] = Math.Max(range[2], x2);
1788
                range[3] = Math.Max(range[3], y2);
1789

    
1790
                for (int i = 1; i < int.MaxValue; i++)
1791
                {
1792
                    double connX = 0;
1793
                    double connY = 0;
1794
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1795
                        points.Add(new double[] { connX, connY });
1796
                    else
1797
                        break;
1798
                }
1799

    
1800
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1801
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1802

    
1803
                ReleaseCOMObjects(_ChildSymbol);
1804
            }
1805
        }
1806

    
1807
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1808
        {
1809
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1810
            if (_ChildSymbol != null)
1811
            {
1812
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1813
                double x1 = 0;
1814
                double y1 = 0;
1815
                double x2 = 0;
1816
                double y2 = 0;
1817
                symbol2d.Range(out x1, out y1, out x2, out y2);
1818
                range[0] = Math.Min(range[0], x1);
1819
                range[1] = Math.Min(range[1], y1);
1820
                range[2] = Math.Max(range[2], x2);
1821
                range[3] = Math.Max(range[3], y2);
1822

    
1823
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1824
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1825
                ReleaseCOMObjects(_ChildSymbol);
1826
            }
1827
        }
1828

    
1829
        /// <summary>
1830
        /// Label Symbol Modeling
1831
        /// </summary>
1832
        /// <param name="symbol"></param>
1833
        private void LabelSymbolModeling(Symbol symbol)
1834
        {
1835
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1836
            {
1837
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1838
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1839
                    return;
1840
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1841

    
1842
                string symbolUID = itemAttribute.VALUE;
1843
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1844
                if (targetItem != null &&
1845
                    (targetItem.GetType() == typeof(Symbol) ||
1846
                    targetItem.GetType() == typeof(Equipment)))
1847
                {
1848
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1849
                    string sRep = null;
1850
                    if (targetItem.GetType() == typeof(Symbol))
1851
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1852
                    else if (targetItem.GetType() == typeof(Equipment))
1853
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1854
                    if (!string.IsNullOrEmpty(sRep))
1855
                    {
1856
                        // LEADER Line 검사
1857
                        bool leaderLine = false;
1858
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1859
                        if (symbolMapping != null)
1860
                            leaderLine = symbolMapping.LEADERLINE;
1861

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

    
1866
                        //Leader 선 센터로
1867
                        if (_LMLabelPresist != null)
1868
                        {
1869
                            // Target Item에 Label의 Attribute Input
1870
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1871

    
1872
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1873
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1874
                            if (dependency != null)
1875
                            {
1876
                                bool result = false;
1877
                                foreach (var attributes in dependency.AttributeSets)
1878
                                {
1879
                                    foreach (var attribute in attributes)
1880
                                    {
1881
                                        string name = attribute.Name;
1882
                                        string value = attribute.GetValue().ToString();
1883
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1884
                                        {
1885
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1886
                                            {
1887
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1888
                                                {
1889
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1890
                                                    double prevX = _TargetItem.get_XCoordinate();
1891
                                                    double prevY = _TargetItem.get_YCoordinate();
1892
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1893
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1894
                                                    result = true;
1895
                                                    break;
1896
                                                }
1897
                                            }
1898
                                        }
1899

    
1900
                                        if (result)
1901
                                            break;
1902
                                    }
1903

    
1904
                                    if (result)
1905
                                        break;
1906
                                }
1907
                            }
1908

    
1909
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1910
                            _LMLabelPresist.Commit();
1911
                            ReleaseCOMObjects(_LMLabelPresist);
1912
                        }
1913

    
1914
                        ReleaseCOMObjects(_TargetItem);
1915
                    }
1916
                }
1917
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1918
                {
1919
                    Line targetLine = targetItem as Line;
1920
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1921
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1922
                    if (connectedLMConnector != null)
1923
                    {
1924
                        // Target Item에 Label의 Attribute Input
1925
                        InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1926

    
1927
                        // LEADER Line 검사
1928
                        bool leaderLine = false;
1929
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1930
                        if (symbolMapping != null)
1931
                            leaderLine = symbolMapping.LEADERLINE;
1932

    
1933
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: symbol.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1934
                        if (_LMLabelPresist != null)
1935
                        {
1936
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1937
                            _LMLabelPresist.Commit();
1938
                            ReleaseCOMObjects(_LMLabelPresist);
1939
                        }
1940
                        ReleaseCOMObjects(connectedLMConnector);
1941
                    }
1942

    
1943
                    foreach (var item in connectorVertices)
1944
                        if (item.Key != null)
1945
                            ReleaseCOMObjects(item.Key);
1946
                }
1947
            }
1948
        }
1949

    
1950
        /// <summary>
1951
        /// Equipment를 실제로 Modeling 메서드
1952
        /// </summary>
1953
        /// <param name="equipment"></param>
1954
        private void EquipmentModeling(Equipment equipment)
1955
        {
1956
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1957
                return;
1958

    
1959
            LMSymbol _LMSymbol = null;
1960
            LMSymbol targetItem = null;
1961
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1962
            double x = equipment.SPPID.ORIGINAL_X;
1963
            double y = equipment.SPPID.ORIGINAL_Y;
1964
            int mirror = 0;
1965
            double angle = equipment.ANGLE;
1966

    
1967
            // Mirror 계산
1968
            if (equipment.FLIP == 1)
1969
            {
1970
                mirror = 1;
1971
                if (angle == Math.PI || angle == 0)
1972
                    angle += Math.PI;
1973
            }
1974

    
1975
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1976

    
1977
            Connector connector = equipment.CONNECTORS.Find(conn =>
1978
            !string.IsNullOrEmpty(conn.CONNECTEDITEM) &&
1979
            conn.CONNECTEDITEM != "None" &&
1980
            conn.ConnectedObject.GetType() == typeof(Equipment));
1981

    
1982
            if (connector != null)
1983
            {
1984
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1985
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1986
                if (connEquipment != null)
1987
                {
1988
                    //if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1989
                    //    EquipmentModeling(connEquipment);
1990

    
1991
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1992
                    {
1993
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1994
                        if (targetItem != null)
1995
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1996
                        else
1997
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1998
                    }
1999
                    else
2000
                    {
2001
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2002
                    }
2003
                }
2004
                else if (connVendorPackage != null)
2005
                {
2006
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
2007
                    {
2008
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
2009
                        if (targetItem != null)
2010
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2011
                        else
2012
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2013
                    }
2014
                }
2015
                else
2016
                {
2017
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2018
                }
2019
            }
2020
            else
2021
            {
2022
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2023
            }
2024

    
2025
            if (_LMSymbol != null)
2026
            {
2027
                _LMSymbol.Commit();
2028
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2029
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
2030
                ReleaseCOMObjects(_LMSymbol);
2031
            }
2032

    
2033
            if (targetItem != null)
2034
            {
2035
                ReleaseCOMObjects(targetItem);
2036
            }
2037

    
2038
            ReleaseCOMObjects(_LMSymbol);
2039
        }
2040

    
2041
        private void VendorPackageModeling(VendorPackage vendorPackage)
2042
        {
2043
            ETCSetting setting = ETCSetting.GetInstance();
2044
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2045
            {
2046
                string symbolPath = setting.VendorPackageSymbolPath;
2047
                double x = vendorPackage.SPPID.ORIGINAL_X;
2048
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2049

    
2050
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2051
                if (symbol != null)
2052
                {
2053
                    symbol.Commit();
2054
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2055
                }
2056

    
2057
                ReleaseCOMObjects(symbol);
2058
                symbol = null;
2059
            }
2060
        }
2061

    
2062
        /// <summary>
2063
        /// 첫 진입점
2064
        /// </summary>
2065
        /// <param name="symbol"></param>
2066
        private void SymbolModelingBySymbol(Symbol symbol)
2067
        {
2068
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2069
            List<object> endObjects = new List<object>();
2070
            endObjects.Add(symbol);
2071

    
2072
            /// 심볼에 연결되어 있는 항목들을 모델링한다
2073
            foreach (var connector in symbol.CONNECTORS)
2074
            {
2075
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2076
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2077
                {
2078
                    endObjects.Add(connItem);
2079
                    if (connItem.GetType() == typeof(Symbol))
2080
                    {
2081
                        Symbol connSymbol = connItem as Symbol;
2082
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2083
                        {
2084
                            SymbolModeling(connSymbol, symbol);
2085
                        }
2086
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2087
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2088
                    }
2089
                    else if (connItem.GetType() == typeof(Line))
2090
                    {
2091
                        Line connLine = connItem as Line;
2092
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2093
                    }
2094
                }
2095
            }
2096
        }
2097

    
2098
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2099
        {
2100
            foreach (var connector in symbol.CONNECTORS)
2101
            {
2102
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2103
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2104
                {
2105
                    if (!endObjects.Contains(connItem))
2106
                    {
2107
                        endObjects.Add(connItem);
2108
                        if (connItem.GetType() == typeof(Symbol))
2109
                        {
2110
                            Symbol connSymbol = connItem as Symbol;
2111
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2112
                            {
2113
                                SymbolModeling(connSymbol, symbol);
2114
                            }
2115
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2116
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2117
                        }
2118
                        else if (connItem.GetType() == typeof(Line))
2119
                        {
2120
                            Line connLine = connItem as Line;
2121
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2122
                        }
2123
                    }
2124
                }
2125
            }
2126
        }
2127

    
2128
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2129
        {
2130
            foreach (var connector in line.CONNECTORS)
2131
            {
2132
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2133
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2134
                {
2135
                    if (!endObjects.Contains(connItem))
2136
                    {
2137
                        endObjects.Add(connItem);
2138
                        if (connItem.GetType() == typeof(Symbol))
2139
                        {
2140
                            Symbol connSymbol = connItem as Symbol;
2141
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2142
                            {
2143
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2144
                                int branchCount = 0;
2145
                                if (connLine != null)
2146
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2147

    
2148
                                List<Symbol> group = new List<Symbol>();
2149
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2150
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2151
                                List<Symbol> endModelingGroup = new List<Symbol>();
2152
                                if (priority != null)
2153
                                {
2154
                                    SymbolGroupModeling(priority, group);
2155

    
2156
                                    // Range 겹치는지 확인해야함
2157
                                    double[] prevRange = null;
2158
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2159
                                    double[] groupRange = null;
2160
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2161

    
2162
                                    double distanceX = 0;
2163
                                    double distanceY = 0;
2164
                                    bool overlapX = false;
2165
                                    bool overlapY = false;
2166
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2167
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2168
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2169
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2170
                                    {
2171
                                        RemoveSymbol(group);
2172
                                        foreach (var _temp in group)
2173
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2174

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

    
2195
                                                SymbolGroupModeling(priority, group);
2196
                                            }
2197
                                        }
2198
                                    }
2199
                                }
2200
                                else
2201
                                {
2202
                                    SymbolModeling(connSymbol, null);
2203
                                    // Range 겹치는지 확인해야함
2204
                                    double[] prevRange = null;
2205
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2206
                                    double[] connRange = null;
2207
                                    GetSPPIDSymbolRange(connSymbol, ref connRange, bForGraphic: true);
2208

    
2209
                                    double distanceX = 0;
2210
                                    double distanceY = 0;
2211
                                    bool overlapX = false;
2212
                                    bool overlapY = false;
2213
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2214
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2215
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2216
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2217
                                    {
2218
                                        RemoveSymbol(connSymbol);
2219
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2220

    
2221
                                        SymbolModeling(connSymbol, null);
2222
                                    }
2223
                                    else if (branchCount > 0)
2224
                                    {
2225
                                        LMConnector _connector = JustLineModeling(connLine);
2226
                                        if (_connector != null)
2227
                                        {
2228
                                            double distance = GetConnectorDistance(_connector);
2229
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2230
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2231
                                            _connector.Commit();
2232
                                            ReleaseCOMObjects(_connector);
2233
                                            _connector = null;
2234
                                            if (cellCount < branchCount + 1)
2235
                                            {
2236
                                                int moveCount = branchCount - cellCount;
2237
                                                RemoveSymbol(group);
2238
                                                foreach (var _temp in group)
2239
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2240

    
2241
                                                SymbolGroupModeling(priority, group);
2242
                                            }
2243
                                        }
2244
                                    }
2245
                                }
2246
                            }
2247
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2248
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2249
                        }
2250
                        else if (connItem.GetType() == typeof(Line))
2251
                        {
2252
                            Line connLine = connItem as Line;
2253
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2254
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2255
                        }
2256
                    }
2257
                }
2258
            }
2259
        }
2260

    
2261
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2262
        {
2263
            List<Symbol> endModelingGroup = new List<Symbol>();
2264
            SymbolModeling(firstSymbol, null);
2265
            endModelingGroup.Add(firstSymbol);
2266
            while (endModelingGroup.Count != group.Count)
2267
            {
2268
                foreach (var _symbol in group)
2269
                {
2270
                    if (!endModelingGroup.Contains(_symbol))
2271
                    {
2272
                        foreach (var _connector in _symbol.CONNECTORS)
2273
                        {
2274
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2275
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2276
                            {
2277
                                SymbolModeling(_symbol, _connSymbol);
2278
                                endModelingGroup.Add(_symbol);
2279
                                break;
2280
                            }
2281
                        }
2282
                    }
2283
                }
2284
            }
2285
        }
2286

    
2287
        /// <summary>
2288
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2289
        /// </summary>
2290
        /// <param name="childSymbol"></param>
2291
        /// <param name="parentSymbol"></param>
2292
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2293
        {
2294
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2295
            double x1 = 0;
2296
            double x2 = 0;
2297
            double y1 = 0;
2298
            double y2 = 0;
2299
            symbol2d.Range(out x1, out y1, out x2, out y2);
2300

    
2301
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2302
            if (_LMSymbol != null)
2303
            {
2304
                _LMSymbol.Commit();
2305
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2306
                foreach (var item in childSymbol.ChildSymbols)
2307
                    CreateChildSymbol(item, _LMSymbol, parent);
2308
            }
2309

    
2310

    
2311
            ReleaseCOMObjects(_LMSymbol);
2312
        }
2313
        double index = 0;
2314
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2315
        {
2316
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2317
                return;
2318

    
2319
            List<Line> group = new List<Line>();
2320
            GetConnectedLineGroup(line, group);
2321
            LineCoordinateCorrection(group);
2322

    
2323
            foreach (var groupLine in group)
2324
            {
2325
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2326
                {
2327
                    BranchLines.Add(groupLine);
2328
                    continue;
2329
                }
2330

    
2331
                bool diagonal = false;
2332
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2333
                    diagonal = true;
2334
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2335
                LMSymbol _LMSymbolStart = null;
2336
                LMSymbol _LMSymbolEnd = null;
2337
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2338
                foreach (var connector in groupLine.CONNECTORS)
2339
                {
2340
                    double x = 0;
2341
                    double y = 0;
2342
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2343
                    if (connector.ConnectedObject == null)
2344
                        placeRunInputs.AddPoint(x, y);
2345
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2346
                    {
2347
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2348
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2349
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2350
                        {
2351
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2352
                            if (_LMSymbolStart != null)
2353
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2354
                            else
2355
                                placeRunInputs.AddPoint(x, y);
2356
                        }
2357
                        else
2358
                        {
2359
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2360
                            if (_LMSymbolEnd != null)
2361
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2362
                            else
2363
                                placeRunInputs.AddPoint(x, y);
2364
                        }
2365
                    }
2366
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2367
                    {
2368
                        Line targetLine = connector.ConnectedObject as Line;
2369
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2370
                        {
2371
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2372
                            if (targetConnector != null)
2373
                            {
2374
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2375
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2376
                            }
2377
                            else
2378
                            {
2379
                                placeRunInputs.AddPoint( x, y);
2380
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2381
                            }
2382
                        }
2383
                        else
2384
                        {
2385
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2386
                            {
2387
                                index += 0.01;
2388
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2389
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2390
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2391
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2392
                                else
2393
                                {
2394
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2395
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2396
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2397
                                    else
2398
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2399
                                }
2400
                            }
2401

    
2402
                            placeRunInputs.AddPoint(x, y);
2403

    
2404
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2405
                            {
2406
                                index += 0.01;
2407
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2408
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2409
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2410
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2411
                                else
2412
                                {
2413
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2414
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2415
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2416
                                    else
2417
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2418
                                }
2419
                            }
2420
                        }
2421
                    }
2422
                    else
2423
                        placeRunInputs.AddPoint(x, y);
2424
                }
2425

    
2426
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2427
                if (_lMConnector != null)
2428
                {
2429
                    _lMConnector.Commit();
2430
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2431

    
2432
                    bool bRemodelingStart = false;
2433
                    if (_LMSymbolStart != null)
2434
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2435
                    bool bRemodelingEnd = false;
2436
                    if (_LMSymbolEnd != null)
2437
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2438

    
2439
                    if (bRemodelingStart || bRemodelingEnd)
2440
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2441

    
2442
                    FlowMarkModeling(groupLine);
2443

    
2444
                    ReleaseCOMObjects(_lMConnector);
2445

    
2446
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2447
                    if (modelItem != null)
2448
                    {
2449
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2450
                        if (attribute != null)
2451
                            attribute.set_Value("End 1 is upstream (Inlet)");
2452
                        modelItem.Commit();
2453
                    }
2454
                    ReleaseCOMObjects(modelItem);
2455
                    modelItem = null;
2456
                }
2457
                else if (!isBranchModeling)
2458
                {
2459
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2460
                }
2461

    
2462
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2463
                x.ConnectedObject != null &&
2464
                x.ConnectedObject.GetType() == typeof(Line) &&
2465
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2466
                .Select(x => x.ConnectedObject)
2467
                .ToList();
2468

    
2469
                foreach (var item in removeLines)
2470
                    RemoveLineForModeling(item as Line);
2471

    
2472
                ReleaseCOMObjects(_LMAItem);
2473
                _LMAItem = null;
2474
                ReleaseCOMObjects(placeRunInputs);
2475
                placeRunInputs = null;
2476
                ReleaseCOMObjects(_LMSymbolStart);
2477
                _LMSymbolStart = null;
2478
                ReleaseCOMObjects(_LMSymbolEnd);
2479
                _LMSymbolEnd = null;
2480

    
2481
                if (isBranchModeling && BranchLines.Contains(groupLine))
2482
                    BranchLines.Remove(groupLine);
2483
            }
2484
        }
2485

    
2486
        private LMConnector JustLineModeling(Line line)
2487
        {
2488
            bool diagonal = false;
2489
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2490
                diagonal = true;
2491
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2492
            LMSymbol _LMSymbolStart = null;
2493
            LMSymbol _LMSymbolEnd = null;
2494
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2495
            foreach (var connector in line.CONNECTORS)
2496
            {
2497
                double x = 0;
2498
                double y = 0;
2499
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2500
                if (connector.ConnectedObject == null)
2501
                {
2502
                    placeRunInputs.AddPoint(x, y);
2503
                }
2504
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2505
                {
2506
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2507
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2508
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2509
                    {
2510
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2511
                        if (_LMSymbolStart != null)
2512
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2513
                        else
2514
                            placeRunInputs.AddPoint(x, y);
2515
                    }
2516
                    else
2517
                    {
2518
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2519
                        if (_LMSymbolEnd != null)
2520
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2521
                        else
2522
                            placeRunInputs.AddPoint(x, y);
2523
                    }
2524
                }
2525
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2526
                {
2527
                    Line targetLine = connector.ConnectedObject as Line;
2528
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2529
                    {
2530
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2531
                        if (targetConnector != null)
2532
                        {
2533
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2534
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2535
                        }
2536
                        else
2537
                        {
2538
                            placeRunInputs.AddPoint(x, y);
2539
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2540
                        }
2541
                    }
2542
                    else
2543
                        placeRunInputs.AddPoint(x, y);
2544
                }
2545
            }
2546

    
2547
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2548
            if (_lMConnector != null)
2549
                _lMConnector.Commit();
2550

    
2551
            ReleaseCOMObjects(_LMAItem);
2552
            _LMAItem = null;
2553
            ReleaseCOMObjects(placeRunInputs);
2554
            placeRunInputs = null;
2555
            ReleaseCOMObjects(_LMSymbolStart);
2556
            _LMSymbolStart = null;
2557
            ReleaseCOMObjects(_LMSymbolEnd);
2558
            _LMSymbolEnd = null;
2559

    
2560
            return _lMConnector;
2561
        }
2562

    
2563
        private void RemoveLineForModeling(Line line)
2564
        {
2565
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2566
            if (modelItem != null)
2567
            {
2568
                foreach (LMRepresentation rep in modelItem.Representations)
2569
                {
2570
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2571
                    {
2572
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2573
                        dynamic OID = rep.get_GraphicOID().ToString();
2574
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2575
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2576
                        int verticesCount = lineStringGeometry.VertexCount;
2577
                        double[] vertices = null;
2578
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2579
                        for (int i = 0; i < verticesCount; i++)
2580
                        {
2581
                            double x = 0;
2582
                            double y = 0;
2583
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2584
                            if (verticesCount == 2 && (x < 0 || y < 0))
2585
                                _placement.PIDRemovePlacement(rep);
2586
                        }
2587
                        ReleaseCOMObjects(_LMConnector);
2588
                    }
2589
                }
2590

    
2591
                ReleaseCOMObjects(modelItem);
2592
            }
2593
        }
2594

    
2595
        private void RemoveLine(Line line)
2596
        {
2597
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2598
            if (modelItem != null)
2599
            {
2600
                foreach (LMRepresentation rep in modelItem.Representations)
2601
                {
2602
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2603
                        _placement.PIDRemovePlacement(rep);
2604
                }
2605
                ReleaseCOMObjects(modelItem);
2606
            }
2607
            line.SPPID.ModelItemId = null;
2608
        }
2609

    
2610
        private void GetConnectedLineGroup(Line line, List<Line> group)
2611
        {
2612
            if (!group.Contains(line))
2613
                group.Add(line);
2614
            foreach (var connector in line.CONNECTORS)
2615
            {
2616
                if (connector.ConnectedObject != null &&
2617
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2618
                    !group.Contains(connector.ConnectedObject) &&
2619
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2620
                {
2621
                    Line connLine = connector.ConnectedObject as Line;
2622
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2623
                    {
2624
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2625
                            group.Insert(0, connLine);
2626
                        else
2627
                            group.Add(connLine);
2628
                        GetConnectedLineGroup(connLine, group);
2629
                    }
2630
                }
2631
            }
2632
        }
2633

    
2634
        private void LineCoordinateCorrection(List<Line> group)
2635
        {
2636
            // 순서대로 전 Item 기준 정렬
2637
            LineCoordinateCorrectionByStart(group);
2638

    
2639
            // 역으로 심볼이 있을 경우 좌표 보정
2640
            LineCoordinateCorrectionForLastLine(group);
2641
        }
2642

    
2643
        private void LineCoordinateCorrectionByStart(List<Line> group)
2644
        {
2645
            for (int i = 0; i < group.Count; i++)
2646
            {
2647
                Line line = group[i];
2648
                if (i == 0)
2649
                {
2650
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2651
                    if (symbolConnector != null)
2652
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2653
                }
2654
                else if (i != 0)
2655
                {
2656
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2657
                }
2658
            }
2659
        }
2660

    
2661
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2662
        {
2663
            Line checkLine = group[group.Count - 1];
2664
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2665
            if (lastSymbolConnector != null)
2666
            {
2667
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2668
                for (int i = group.Count - 2; i >= 0; i--)
2669
                {
2670
                    Line line = group[i + 1];
2671
                    Line prevLine = group[i];
2672

    
2673
                    // 같으면 보정
2674
                    if (line.SlopeType == prevLine.SlopeType)
2675
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2676
                    else
2677
                    {
2678
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2679
                        {
2680
                            double prevX = 0;
2681
                            double prevY = 0;
2682
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2683
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2684

    
2685
                            double x = 0;
2686
                            double y = 0;
2687
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2688
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2689
                        }
2690
                        else if (line.SlopeType == SlopeType.VERTICAL)
2691
                        {
2692
                            double prevX = 0;
2693
                            double prevY = 0;
2694
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2695
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2696

    
2697
                            double x = 0;
2698
                            double y = 0;
2699
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2700
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2701
                        }
2702
                        break;
2703
                    }
2704
                }
2705
            }
2706
        }
2707

    
2708
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2709
        {
2710
            double x = 0;
2711
            double y = 0;
2712
            if (connItem.GetType() == typeof(Symbol))
2713
            {
2714
                Symbol targetSymbol = connItem as Symbol;
2715
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2716
                if (targetConnector != null)
2717
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2718
                else
2719
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2720
            }
2721
            else if (connItem.GetType() == typeof(Line))
2722
            {
2723
                Line targetLine = connItem as Line;
2724
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2725
            }
2726

    
2727
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2728
        }
2729

    
2730
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2731
        {
2732
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2733
            int index = line.CONNECTORS.IndexOf(connector);
2734
            if (index == 0)
2735
            {
2736
                line.SPPID.START_X = x;
2737
                line.SPPID.START_Y = y;
2738
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2739
                    line.SPPID.END_Y = y;
2740
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2741
                    line.SPPID.END_X = x;
2742
            }
2743
            else
2744
            {
2745
                line.SPPID.END_X = x;
2746
                line.SPPID.END_Y = y;
2747
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2748
                    line.SPPID.START_Y = y;
2749
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2750
                    line.SPPID.START_X = x;
2751
            }
2752
        }
2753

    
2754
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2755
        {
2756
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2757
            int index = line.CONNECTORS.IndexOf(connector);
2758
            if (index == 0)
2759
            {
2760
                line.SPPID.START_X = x;
2761
                if (line.SlopeType == SlopeType.VERTICAL)
2762
                    line.SPPID.END_X = x;
2763
            }
2764
            else
2765
            {
2766
                line.SPPID.END_X = x;
2767
                if (line.SlopeType == SlopeType.VERTICAL)
2768
                    line.SPPID.START_X = x;
2769
            }
2770
        }
2771

    
2772
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2773
        {
2774
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2775
            int index = line.CONNECTORS.IndexOf(connector);
2776
            if (index == 0)
2777
            {
2778
                line.SPPID.START_Y = y;
2779
                if (line.SlopeType == SlopeType.HORIZONTAL)
2780
                    line.SPPID.END_Y = y;
2781
            }
2782
            else
2783
            {
2784
                line.SPPID.END_Y = y;
2785
                if (line.SlopeType == SlopeType.HORIZONTAL)
2786
                    line.SPPID.START_Y = y;
2787
            }
2788
        }
2789

    
2790
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2791
        {
2792
            if (symbol != null)
2793
            {
2794
                string repID = symbol.AsLMRepresentation().Id;
2795
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2796
                string lineUID = line.UID;
2797

    
2798
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2799
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2800
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2801

    
2802
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2803
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2804
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2805

    
2806
                if (startSpecBreak != null || startEndBreak != null)
2807
                    result = true;
2808
            }
2809
        }
2810

    
2811
        /// <summary>
2812
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2813
        /// </summary>
2814
        /// <param name="lines"></param>
2815
        /// <param name="prevLMConnector"></param>
2816
        /// <param name="startSymbol"></param>
2817
        /// <param name="endSymbol"></param>
2818
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2819
        {
2820
            string symbolPath = string.Empty;
2821
            #region get symbol path
2822
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2823
            symbolPath = GetSPPIDFileName(modelItem);
2824
            ReleaseCOMObjects(modelItem);
2825
            #endregion
2826
            bool diagonal = false;
2827
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2828
                diagonal = true;
2829
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2830
            LMConnector newConnector = null;
2831
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2832
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2833
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2834
            int verticesCount = lineStringGeometry.VertexCount;
2835
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2836

    
2837
            List<double[]> vertices = new List<double[]>();
2838
            for (int i = 1; i <= verticesCount; i++)
2839
            {
2840
                double x = 0;
2841
                double y = 0;
2842
                lineStringGeometry.GetVertex(i, ref x, ref y);
2843
                vertices.Add(new double[] { x, y });
2844
            }
2845

    
2846
            for (int i = 0; i < vertices.Count; i++)
2847
            {
2848
                double[] points = vertices[i];
2849
                // 시작 심볼이 있고 첫번째 좌표일 때
2850
                if (startSymbol != null && i == 0)
2851
                {
2852
                    if (bStart)
2853
                    {
2854
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2855
                        if (slopeType == SlopeType.HORIZONTAL)
2856
                            placeRunInputs.AddPoint(points[0], -0.1);
2857
                        else if (slopeType == SlopeType.VERTICAL)
2858
                            placeRunInputs.AddPoint(-0.1, points[1]);
2859
                        else
2860
                            placeRunInputs.AddPoint(points[0], -0.1);
2861

    
2862
                        placeRunInputs.AddPoint(points[0], points[1]);
2863
                    }
2864
                    else
2865
                    {
2866
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2867
                    }
2868
                }
2869
                // 마지막 심볼이 있고 마지막 좌표일 때
2870
                else if (endSymbol != null && i == vertices.Count - 1)
2871
                {
2872
                    if (bEnd)
2873
                    {
2874
                        placeRunInputs.AddPoint(points[0], points[1]);
2875

    
2876
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2877
                        if (slopeType == SlopeType.HORIZONTAL)
2878
                            placeRunInputs.AddPoint(points[0], -0.1);
2879
                        else if (slopeType == SlopeType.VERTICAL)
2880
                            placeRunInputs.AddPoint(-0.1, points[1]);
2881
                        else
2882
                            placeRunInputs.AddPoint(points[0], -0.1);
2883
                    }
2884
                    else
2885
                    {
2886
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2887
                    }
2888
                }
2889
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2890
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2891
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2892
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2893
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2894
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2895
                else
2896
                    placeRunInputs.AddPoint(points[0], points[1]);
2897
            }
2898

    
2899
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2900
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2901

    
2902
            ReleaseCOMObjects(placeRunInputs);
2903
            ReleaseCOMObjects(_LMAItem);
2904
            ReleaseCOMObjects(modelItem);
2905

    
2906
            if (newConnector != null)
2907
            {
2908
                newConnector.Commit();
2909
                if (startSymbol != null && bStart)
2910
                {
2911
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2912
                    placeRunInputs = new PlaceRunInputs();
2913
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2914
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2915
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2916
                    if (_LMConnector != null)
2917
                    {
2918
                        _LMConnector.Commit();
2919
                        RemoveConnectorForReModelingLine(newConnector);
2920
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2921
                        ReleaseCOMObjects(_LMConnector);
2922
                    }
2923
                    ReleaseCOMObjects(placeRunInputs);
2924
                    ReleaseCOMObjects(_LMAItem);
2925
                }
2926

    
2927
                if (endSymbol != null && bEnd)
2928
                {
2929
                    if (startSymbol != null)
2930
                    {
2931
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2932
                        newConnector = dicVertices.First().Key;
2933
                    }
2934

    
2935
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2936
                    placeRunInputs = new PlaceRunInputs();
2937
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2938
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2939
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2940
                    if (_LMConnector != null)
2941
                    {
2942
                        _LMConnector.Commit();
2943
                        RemoveConnectorForReModelingLine(newConnector);
2944
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2945
                        ReleaseCOMObjects(_LMConnector);
2946
                    }
2947
                    ReleaseCOMObjects(placeRunInputs);
2948
                    ReleaseCOMObjects(_LMAItem);
2949
                }
2950

    
2951
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2952
                ReleaseCOMObjects(newConnector);
2953
            }
2954

    
2955
            ReleaseCOMObjects(modelItem);
2956
        }
2957

    
2958
        /// <summary>
2959
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2960
        /// </summary>
2961
        /// <param name="connector"></param>
2962
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2963
        {
2964
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2965
            foreach (var item in dicVertices)
2966
            {
2967
                if (item.Value.Count == 2)
2968
                {
2969
                    bool result = false;
2970
                    foreach (var point in item.Value)
2971
                    {
2972
                        if (point[0] < 0 || point[1] < 0)
2973
                        {
2974
                            result = true;
2975
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2976
                            break;
2977
                        }
2978
                    }
2979

    
2980
                    if (result)
2981
                        break;
2982
                }
2983
            }
2984
            foreach (var item in dicVertices)
2985
                ReleaseCOMObjects(item.Key);
2986
        }
2987

    
2988
        /// <summary>
2989
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2990
        /// </summary>
2991
        /// <param name="symbol"></param>
2992
        /// <param name="line"></param>
2993
        /// <returns></returns>
2994
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2995
        {
2996
            LMSymbol _LMSymbol = null;
2997
            foreach (var connector in symbol.CONNECTORS)
2998
            {
2999
                if (connector.CONNECTEDITEM == line.UID)
3000
                {
3001
                    if (connector.Index == 0)
3002
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3003
                    else
3004
                    {
3005
                        ChildSymbol child = null;
3006
                        foreach (var childSymbol in symbol.ChildSymbols)
3007
                        {
3008
                            if (childSymbol.Connectors.Contains(connector))
3009
                                child = childSymbol;
3010
                            else
3011
                                child = GetChildSymbolByConnector(childSymbol, connector);
3012

    
3013
                            if (child != null)
3014
                                break;
3015
                        }
3016

    
3017
                        if (child != null)
3018
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3019
                    }
3020

    
3021
                    break;
3022
                }
3023
            }
3024

    
3025
            return _LMSymbol;
3026
        }
3027

    
3028
        /// <summary>
3029
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3030
        /// </summary>
3031
        /// <param name="item"></param>
3032
        /// <param name="connector"></param>
3033
        /// <returns></returns>
3034
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3035
        {
3036
            foreach (var childSymbol in item.ChildSymbols)
3037
            {
3038
                if (childSymbol.Connectors.Contains(connector))
3039
                    return childSymbol;
3040
                else
3041
                    return GetChildSymbolByConnector(childSymbol, connector);
3042
            }
3043

    
3044
            return null;
3045
        }
3046

    
3047
        /// <summary>
3048
        /// EndBreak 모델링 메서드
3049
        /// </summary>
3050
        /// <param name="endBreak"></param>
3051
        private void EndBreakModeling(EndBreak endBreak)
3052
        {
3053
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3054
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3055

    
3056
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3057
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3058
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3059

    
3060
            if (targetLMConnector != null)
3061
            {
3062
                // LEADER Line 검사
3063
                bool leaderLine = false;
3064
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3065
                if (symbolMapping != null)
3066
                    leaderLine = symbolMapping.LEADERLINE;
3067

    
3068
                SegmentLocation location;
3069
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3070
                Array array = null;
3071
                if (point != null)
3072
                    array = new double[] { 0, point[0], point[1] };
3073
                else
3074
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3075
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3076
                if (_LmLabelPersist != null)
3077
                {
3078
                    _LmLabelPersist.Commit();
3079
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3080
                    if (_LmLabelPersist.ModelItemObject != null)
3081
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3082
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3083

    
3084
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3085

    
3086
                    ReleaseCOMObjects(_LmLabelPersist);
3087
                }
3088
                ReleaseCOMObjects(targetLMConnector);
3089
            }
3090
            else
3091
            {
3092
                Log.Write("End Break UID : " + endBreak.UID);
3093
                Log.Write("Can't find targetLMConnector");
3094
            }
3095
        }
3096

    
3097
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3098
        {
3099
            double x = 0, y = 0;
3100
            if (location.HasFlag(SegmentLocation.Up))
3101
                y = GridSetting.GetInstance().Length * 3;
3102
            else if (location.HasFlag(SegmentLocation.Down))
3103
                y = -GridSetting.GetInstance().Length * 3;
3104

    
3105
            if (location.HasFlag(SegmentLocation.Right))
3106
                x = GridSetting.GetInstance().Length * 3;
3107
            else if (location.HasFlag(SegmentLocation.Left))
3108
                x = -GridSetting.GetInstance().Length * 3;
3109

    
3110
            if (x != 0 || y != 0)
3111
            {
3112
                radApp.ActiveSelectSet.RemoveAll();
3113
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3114
                if (dependency != null)
3115
                {
3116
                    radApp.ActiveSelectSet.Add(dependency);
3117
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3118
                    transform.DefineByMove2d(x, y);
3119
                    radApp.ActiveSelectSet.Transform(transform, true);
3120
                    radApp.ActiveSelectSet.RemoveAll();
3121
                }
3122
            }
3123
        }
3124

    
3125
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3126
        {
3127
            string symbolPath = string.Empty;
3128
            #region get symbol path
3129
            if (string.IsNullOrEmpty(changeSymbolPath))
3130
            {
3131
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3132
                symbolPath = GetSPPIDFileName(modelItem);
3133
                ReleaseCOMObjects(modelItem);
3134
            }
3135
            else
3136
                symbolPath = changeSymbolPath;
3137
            
3138
            #endregion
3139

    
3140
            LMConnector newConnector = null;
3141
            dynamic OID = connector.get_GraphicOID().ToString();
3142
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3143
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3144
            int verticesCount = lineStringGeometry.VertexCount;
3145
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3146
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3147

    
3148
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3149
            {
3150
                double[] vertices = null;
3151
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3152
                double x = 0;
3153
                double y = 0;
3154
                lineStringGeometry.GetVertex(1, ref x, ref y);
3155

    
3156
                string flowDirection = string.Empty;
3157
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3158
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3159
                    flowDirection = flowAttribute.get_Value().ToString();
3160

    
3161
                if (flowDirection == "End 1 is downstream (Outlet)")
3162
                {
3163
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3164
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3165
                    flowDirection = "End 1 is upstream (Inlet)";
3166
                }
3167
                else
3168
                {
3169
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3170
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3171
                }
3172
                string oldModelItemId = connector.ModelItemID;
3173
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3174
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3175
                newConnector.Commit();
3176
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3177
                if (!string.IsNullOrEmpty(flowDirection))
3178
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3179
                ReleaseCOMObjects(connector);
3180

    
3181
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3182
                {
3183
                    foreach (var repId in line.SPPID.Representations)
3184
                    {
3185
                        LMConnector _connector = dataSource.GetConnector(repId);
3186
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3187
                        {
3188
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3189
                            {
3190
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3191
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3192
                            }
3193
                        }
3194
                        ReleaseCOMObjects(_connector);
3195
                        _connector = null;
3196
                    }
3197
                }
3198
            }
3199

    
3200
            return newConnector;
3201
        }
3202

    
3203
        /// <summary>
3204
        /// SpecBreak Modeling 메서드
3205
        /// </summary>
3206
        /// <param name="specBreak"></param>
3207
        private void SpecBreakModeling(SpecBreak specBreak)
3208
        {
3209
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3210
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3211

    
3212
            if (upStreamObj != null &&
3213
                downStreamObj != null)
3214
            {
3215
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3216
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3217
                    targetLMConnector != null && 
3218
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3219
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3220

    
3221
                if (targetLMConnector != null)
3222
                {
3223
                    foreach (var attribute in specBreak.ATTRIBUTES)
3224
                    {
3225
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3226
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3227
                        {
3228
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3229
                            SegmentLocation location;
3230
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3231
                            Array array = null;
3232
                            if (point != null)
3233
                                array = new double[] { 0, point[0], point[1] };
3234
                            else
3235
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3236
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3237

    
3238
                            if (_LmLabelPersist != null)
3239
                            {
3240
                                _LmLabelPersist.Commit();
3241
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3242
                                if (_LmLabelPersist.ModelItemObject != null)
3243
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3244
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3245

    
3246
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3247

    
3248
                                ReleaseCOMObjects(_LmLabelPersist);
3249
                            }
3250
                        }
3251
                    }
3252

    
3253
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3254
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3255
                    {
3256
                        // temp
3257
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3258
                    }
3259
                    ReleaseCOMObjects(targetLMConnector);
3260
                }
3261
                else
3262
                {
3263
                    Log.Write("Spec Break UID : " + specBreak.UID);
3264
                    Log.Write("Can't find targetLMConnector");
3265
                }
3266
            }
3267
        }
3268

    
3269
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3270
        {
3271
            LMConnector targetConnector = null;
3272
            Symbol targetSymbol = targetObj as Symbol;
3273
            Symbol connectedSymbol = connectedObj as Symbol;
3274
            Line targetLine = targetObj as Line;
3275
            Line connectedLine = connectedObj as Line;
3276
            if (targetSymbol != null && connectedSymbol != null)
3277
            {
3278
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3279
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3280

    
3281
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3282
                {
3283
                    if (connector.get_ItemStatus() != "Active")
3284
                        continue;
3285

    
3286
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3287
                    {
3288
                        targetConnector = connector;
3289
                        break;
3290
                    }
3291
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3292
                    {
3293
                        targetConnector = connector;
3294
                        break;
3295
                    }
3296
                }
3297

    
3298
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3299
                {
3300
                    if (connector.get_ItemStatus() != "Active")
3301
                        continue;
3302

    
3303
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3304
                    {
3305
                        targetConnector = connector;
3306
                        break;
3307
                    }
3308
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3309
                    {
3310
                        targetConnector = connector;
3311
                        break;
3312
                    }
3313
                }
3314

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

    
3323
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3324
                {
3325
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3326
                    {
3327
                        if (targetConnector != null)
3328
                            break;
3329

    
3330
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3331
                        {
3332
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3333

    
3334
                            if (IsConnected(_LMConnector, connectedModelItem))
3335
                                targetConnector = _LMConnector;
3336
                            else
3337
                                ReleaseCOMObjects(_LMConnector);
3338
                        }
3339
                    }
3340

    
3341
                    ReleaseCOMObjects(targetModelItem);
3342
                }
3343
            }
3344
            else
3345
            {
3346
                LMSymbol connectedLMSymbol = null;
3347
                if (connectedSymbol != null)
3348
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3349
                else if (targetSymbol != null)
3350
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3351
                else
3352
                {
3353

    
3354
                }
3355
                LMModelItem targetModelItem = null;
3356
                if (targetLine != null)
3357
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3358
                else if (connectedLine != null)
3359
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3360
                else
3361
                {
3362

    
3363
                }
3364
                if (connectedLMSymbol != null && targetModelItem != null)
3365
                {
3366
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3367
                    {
3368
                        if (connector.get_ItemStatus() != "Active")
3369
                            continue;
3370

    
3371
                        if (IsConnected(connector, targetModelItem))
3372
                        {
3373
                            targetConnector = connector;
3374
                            break;
3375
                        }
3376
                    }
3377

    
3378
                    if (targetConnector == null)
3379
                    {
3380
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3381
                        {
3382
                            if (connector.get_ItemStatus() != "Active")
3383
                                continue;
3384

    
3385
                            if (IsConnected(connector, targetModelItem))
3386
                            {
3387
                                targetConnector = connector;
3388
                                break;
3389
                            }
3390
                        }
3391
                    }
3392
                }
3393

    
3394
            }
3395

    
3396
            return targetConnector;
3397
        }
3398

    
3399
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
3400
        {
3401
            double[] result = null;
3402
            Line targetLine = targetObj as Line;
3403
            Symbol targetSymbol = targetObj as Symbol;
3404
            Line connLine = connObj as Line;
3405
            Symbol connSymbol = connObj as Symbol;
3406
            location = SegmentLocation.None;
3407
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3408
            {
3409
                result = GetConnectorVertices(targetConnector)[0];
3410
                if (targetSymbol != null && connSymbol != null)
3411
                {
3412
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3413
                    result = new double[] { result[0], result[1] };
3414
                    if (slopeType == SlopeType.HORIZONTAL)
3415
                        location = SegmentLocation.Up;
3416
                    else if (slopeType == SlopeType.VERTICAL)
3417
                        location = SegmentLocation.Right;
3418
                }
3419
                else if (targetLine != null)
3420
                {
3421
                    result = new double[] { result[0], result[1] };
3422
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3423
                        location = SegmentLocation.Up;
3424
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3425
                        location = SegmentLocation.Right;
3426
                }
3427
                else if (connLine != null)
3428
                {
3429
                    result = new double[] { result[0], result[1] };
3430
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3431
                        location = SegmentLocation.Up;
3432
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3433
                        location = SegmentLocation.Right;
3434
                }
3435
            }
3436
            else
3437
            {
3438
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3439
                {
3440
                    Line line = connObj as Line;
3441
                    LMConnector connectedConnector = null;
3442
                    int connIndex = 0;
3443
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3444
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3445

    
3446
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3447

    
3448
                    ReleaseCOMObjects(modelItem);
3449
                    ReleaseCOMObjects(connectedConnector);
3450

    
3451
                    if (vertices.Count > 0)
3452
                    {
3453
                        if (connIndex == 1)
3454
                            result = vertices[0];
3455
                        else if (connIndex == 2)
3456
                            result = vertices[vertices.Count - 1];
3457

    
3458
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3459
                        {
3460
                            result = new double[] { result[0], result[1] };
3461
                            location = SegmentLocation.Up;
3462
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3463
                                location = location | SegmentLocation.Right;
3464
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3465
                                location = location | SegmentLocation.Left;
3466
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3467
                                location = location | SegmentLocation.Left;
3468
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3469
                                location = location | SegmentLocation.Right;
3470
                        }
3471
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3472
                        {
3473
                            result = new double[] { result[0], result[1] };
3474
                            location = SegmentLocation.Right;
3475
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3476
                                location = location | SegmentLocation.Up;
3477
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3478
                                location = location | SegmentLocation.Down;
3479
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3480
                                location = location | SegmentLocation.Down;
3481
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3482
                                location = location | SegmentLocation.Up;
3483
                        }
3484
                            
3485
                    }
3486
                }
3487
                else
3488
                {
3489
                    Log.Write("error in GetSegemtPoint");
3490
                }
3491
            }
3492

    
3493
            return result;
3494
        }
3495

    
3496
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3497
        {
3498
            bool result = false;
3499

    
3500
            foreach (LMRepresentation rep in modelItem.Representations)
3501
            {
3502
                if (result)
3503
                    break;
3504

    
3505
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3506
                {
3507
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3508

    
3509
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3510
                        connector.ConnectItem1SymbolObject != null &&
3511
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3512
                    {
3513
                        result = true;
3514
                        ReleaseCOMObjects(_LMConnector);
3515
                        break;
3516
                    }
3517
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3518
                        connector.ConnectItem2SymbolObject != null &&
3519
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3520
                    {
3521
                        result = true;
3522
                        ReleaseCOMObjects(_LMConnector);
3523
                        break;
3524
                    }
3525
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3526
                        connector.ConnectItem1SymbolObject != null &&
3527
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3528
                    {
3529
                        result = true;
3530
                        ReleaseCOMObjects(_LMConnector);
3531
                        break;
3532
                    }
3533
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3534
                        connector.ConnectItem2SymbolObject != null &&
3535
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3536
                    {
3537
                        result = true;
3538
                        ReleaseCOMObjects(_LMConnector);
3539
                        break;
3540
                    }
3541

    
3542
                    ReleaseCOMObjects(_LMConnector);
3543
                }
3544
            }
3545

    
3546

    
3547
            return result;
3548
        }
3549

    
3550
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3551
        {
3552
            foreach (LMRepresentation rep in modelItem.Representations)
3553
            {
3554
                if (connectedConnector != null)
3555
                    break;
3556

    
3557
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3558
                {
3559
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3560

    
3561
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3562
                        connector.ConnectItem1SymbolObject != null &&
3563
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3564
                    {
3565
                        connectedConnector = _LMConnector;
3566
                        connectorIndex = 1;
3567
                        break;
3568
                    }
3569
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3570
                        connector.ConnectItem2SymbolObject != null &&
3571
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3572
                    {
3573
                        connectedConnector = _LMConnector;
3574
                        connectorIndex = 2;
3575
                        break;
3576
                    }
3577
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3578
                        connector.ConnectItem1SymbolObject != null &&
3579
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3580
                    {
3581
                        connectedConnector = _LMConnector;
3582
                        connectorIndex = 1;
3583
                        break;
3584
                    }
3585
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3586
                        connector.ConnectItem2SymbolObject != null &&
3587
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3588
                    {
3589
                        connectedConnector = _LMConnector;
3590
                        connectorIndex = 2;
3591
                        break;
3592
                    }
3593

    
3594
                    if (connectedConnector == null)
3595
                        ReleaseCOMObjects(_LMConnector);
3596
                }
3597
            }
3598
        }
3599

    
3600
        /// <summary>
3601
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3602
        /// </summary>
3603
        /// <param name="modelItemID1"></param>
3604
        /// <param name="modelItemID2"></param>
3605
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3606
        {
3607
            try
3608
            {
3609
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3610
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3611
                List<double[]> vertices1 = null;
3612
                string graphicOID1 = string.Empty;
3613
                if (connector1 != null)
3614
                {
3615
                    vertices1 = GetConnectorVertices(connector1);
3616
                    graphicOID1 = connector1.get_GraphicOID();
3617
                }
3618
                _LMAItem item1 = modelItem1.AsLMAItem();
3619
                ReleaseCOMObjects(connector1);
3620
                connector1 = null;
3621

    
3622
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3623
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3624
                List<double[]> vertices2 = null;
3625
                string graphicOID2 = string.Empty;
3626
                if (connector2 != null)
3627
                {
3628
                    vertices2 = GetConnectorVertices(connector2);
3629
                    graphicOID2 = connector2.get_GraphicOID();
3630
                }
3631
                _LMAItem item2 = modelItem2.AsLMAItem();
3632
                ReleaseCOMObjects(connector2);
3633
                connector2 = null;
3634

    
3635
                // item2가 item1으로 조인
3636
                _placement.PIDJoinRuns(ref item1, ref item2);
3637
                item1.Commit();
3638
                item2.Commit();
3639

    
3640
                string beforeID = string.Empty;
3641
                string afterID = string.Empty;
3642

    
3643
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3644
                {
3645
                    beforeID = modelItem2.Id;
3646
                    afterID = modelItem1.Id;
3647
                    survivorId = afterID;
3648
                }
3649
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3650
                {
3651
                    beforeID = modelItem1.Id;
3652
                    afterID = modelItem2.Id;
3653
                    survivorId = afterID;
3654
                }
3655
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3656
                {
3657
                    int model1Cnt = GetConnectorCount(modelId1);
3658
                    int model2Cnt = GetConnectorCount(modelId2);
3659
                    if (model1Cnt == 0)
3660
                    {
3661
                        beforeID = modelItem1.Id;
3662
                        afterID = modelItem2.Id;
3663
                        survivorId = afterID;
3664
                    }
3665
                    else if (model2Cnt == 0)
3666
                    {
3667
                        beforeID = modelItem2.Id;
3668
                        afterID = modelItem1.Id;
3669
                        survivorId = afterID;
3670
                    }
3671
                    else
3672
                        survivorId = null;
3673
                }
3674
                else
3675
                {
3676
                    Log.Write("잘못된 경우");
3677
                    survivorId = null;
3678
                }
3679

    
3680
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3681
                {
3682
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3683
                    foreach (var line in lines)
3684
                        line.SPPID.ModelItemId = afterID;
3685
                }
3686

    
3687
                ReleaseCOMObjects(modelItem1);
3688
                ReleaseCOMObjects(item1);
3689
                ReleaseCOMObjects(modelItem2);
3690
                ReleaseCOMObjects(item2);
3691
            }
3692
            catch (Exception ex)
3693
            {
3694
                Log.Write("Join Error");
3695
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3696
            }
3697
        }
3698

    
3699
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3700
        {
3701
            bool result = false;
3702
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3703
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3704
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3705

    
3706
            foreach (var item in endBreaks)
3707
            {
3708
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3709
                {
3710
                    result = true;
3711
                    break;
3712
                }
3713
            }
3714

    
3715
            return result;
3716
        }
3717
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3718
        {
3719
            List<string> temp = new List<string>();
3720
            List<LMConnector> connectors = new List<LMConnector>();
3721
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3722
            {
3723
                if (connector.get_ItemStatus() != "Active")
3724
                    continue;
3725

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

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

    
3737

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

    
3746
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3747
            {
3748
                if (connector.get_ItemStatus() != "Active")
3749
                    continue;
3750

    
3751
                LMModelItem modelItem = connector.ModelItemObject;
3752
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3753
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3754
                    temp.Add(modelItem.Id);
3755

    
3756
                if (temp.Contains(modelItem.Id) &&
3757
                    connOtherSymbol != null &&
3758
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3759
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3760
                    temp.Remove(modelItem.Id);
3761

    
3762
                if (temp.Contains(modelItem.Id))
3763
                    connectors.Add(connector);
3764
                ReleaseCOMObjects(connOtherSymbol);
3765
                connOtherSymbol = null;
3766
                ReleaseCOMObjects(modelItem);
3767
                modelItem = null;
3768
            }
3769

    
3770

    
3771
            List<string> result = new List<string>();
3772
            string originalName = GetSPPIDFileName(modelId);
3773
            foreach (var connector in connectors)
3774
            {
3775
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3776
                if (originalName == fileName)
3777
                    result.Add(connector.ModelItemID);
3778
                else
3779
                {
3780
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3781
                        result.Add(connector.ModelItemID);
3782
                    else
3783
                    {
3784
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3785
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3786
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3787
                            result.Add(connector.ModelItemID);
3788
                    }
3789
                }
3790
            }
3791

    
3792
            foreach (var connector in connectors)
3793
                ReleaseCOMObjects(connector);
3794
            
3795
            return result;
3796

    
3797

    
3798
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3799
            {
3800
                LMSymbol findResult = null;
3801
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3802
                    findResult = connector.ConnectItem1SymbolObject;
3803
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3804
                    findResult = connector.ConnectItem2SymbolObject;
3805

    
3806
                return findResult;
3807
            }
3808
        }
3809

    
3810
        /// <summary>
3811
        /// PipeRun의 좌표를 가져오는 메서드
3812
        /// </summary>
3813
        /// <param name="modelId"></param>
3814
        /// <returns></returns>
3815
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3816
        {
3817
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3818
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3819

    
3820
            if (modelItem != null)
3821
            {
3822
                foreach (LMRepresentation rep in modelItem.Representations)
3823
                {
3824
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3825
                    {
3826
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3827
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3828
                        {
3829
                            ReleaseCOMObjects(_LMConnector);
3830
                            _LMConnector = null;
3831
                            continue;
3832
                        }
3833
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3834
                        dynamic OID = rep.get_GraphicOID().ToString();
3835
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3836
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3837
                        int verticesCount = lineStringGeometry.VertexCount;
3838
                        double[] vertices = null;
3839
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3840
                        for (int i = 0; i < verticesCount; i++)
3841
                        {
3842
                            double x = 0;
3843
                            double y = 0;
3844
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3845
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3846
                        }
3847
                    }
3848
                }
3849

    
3850
                ReleaseCOMObjects(modelItem);
3851
            }
3852

    
3853
            return connectorVertices;
3854
        }
3855

    
3856
        private List<double[]> GetConnectorVertices(LMConnector connector)
3857
        {
3858
            List<double[]> vertices = new List<double[]>();
3859
            if (connector != null)
3860
            {
3861
                dynamic OID = connector.get_GraphicOID().ToString();
3862
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3863
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3864
                int verticesCount = lineStringGeometry.VertexCount;
3865
                double[] value = null;
3866
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3867
                for (int i = 0; i < verticesCount; i++)
3868
                {
3869
                    double x = 0;
3870
                    double y = 0;
3871
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3872
                    vertices.Add(new double[] { x, y });
3873
                }
3874
            }
3875
            return vertices;
3876
        }
3877

    
3878
        private double GetConnectorDistance(LMConnector connector)
3879
        {
3880
            double result = 0;
3881
            List<double[]> vertices = new List<double[]>();
3882
            if (connector != null)
3883
            {
3884
                dynamic OID = connector.get_GraphicOID().ToString();
3885
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3886
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3887
                int verticesCount = lineStringGeometry.VertexCount;
3888
                double[] value = null;
3889
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3890
                for (int i = 0; i < verticesCount; i++)
3891
                {
3892
                    double x = 0;
3893
                    double y = 0;
3894
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3895
                    vertices.Add(new double[] { x, y });
3896
                    if (vertices.Count > 1)
3897
                    {
3898
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3899
                    }
3900
                }
3901
            }
3902
            return result;
3903
        }
3904
        private double[] GetConnectorRange(LMConnector connector)
3905
        {
3906
            double[] result = null;
3907
            List<double[]> vertices = new List<double[]>();
3908
            if (connector != null)
3909
            {
3910
                dynamic OID = connector.get_GraphicOID().ToString();
3911
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3912
                double minX = 0;
3913
                double minY = 0;
3914
                double maxX = 0;
3915
                double maxY = 0;
3916

    
3917
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
3918
                result = new double[] { minX, minY, maxX, maxY };
3919
            }
3920
            return result;
3921
        }
3922
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3923
        {
3924
            List<double[]> vertices = null;
3925
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3926
            if (drawingObject != null)
3927
            {
3928
                vertices = new List<double[]>();
3929
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3930
                int verticesCount = lineStringGeometry.VertexCount;
3931
                double[] value = null;
3932
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3933
                for (int i = 0; i < verticesCount; i++)
3934
                {
3935
                    double x = 0;
3936
                    double y = 0;
3937
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3938
                    vertices.Add(new double[] { x, y });
3939
                }
3940
            }
3941
            return vertices;
3942
        }
3943
        /// <summary>
3944
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3945
        /// </summary>
3946
        /// <param name="connectorVertices"></param>
3947
        /// <param name="connX"></param>
3948
        /// <param name="connY"></param>
3949
        /// <returns></returns>
3950
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3951
        {
3952
            double length = double.MaxValue;
3953
            LMConnector targetConnector = null;
3954
            foreach (var item in connectorVertices)
3955
            {
3956
                List<double[]> points = item.Value;
3957
                for (int i = 0; i < points.Count - 1; i++)
3958
                {
3959
                    double[] point1 = points[i];
3960
                    double[] point2 = points[i + 1];
3961
                    double x1 = Math.Min(point1[0], point2[0]);
3962
                    double y1 = Math.Min(point1[1], point2[1]);
3963
                    double x2 = Math.Max(point1[0], point2[0]);
3964
                    double y2 = Math.Max(point1[1], point2[1]);
3965

    
3966
                    if ((x1 <= connX && x2 >= connX) ||
3967
                        (y1 <= connY && y2 >= connY))
3968
                    {
3969
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3970
                        if (length >= distance)
3971
                        {
3972
                            targetConnector = item.Key;
3973
                            length = distance;
3974
                        }
3975

    
3976
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3977
                        if (length >= distance)
3978
                        {
3979
                            targetConnector = item.Key;
3980
                            length = distance;
3981
                        }
3982
                    }
3983
                }
3984
            }
3985

    
3986
            // 못찾았을때.
3987
            length = double.MaxValue;
3988
            if (targetConnector == null)
3989
            {
3990
                foreach (var item in connectorVertices)
3991
                {
3992
                    List<double[]> points = item.Value;
3993

    
3994
                    foreach (double[] point in points)
3995
                    {
3996
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3997
                        if (length >= distance)
3998
                        {
3999
                            targetConnector = item.Key;
4000
                            length = distance;
4001
                        }
4002
                    }
4003
                }
4004
            }
4005

    
4006
            return targetConnector;
4007
        }
4008

    
4009
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
4010
        {
4011
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4012
            if (vertices.Count == 0)
4013
                return null;
4014

    
4015
            double length = double.MaxValue;
4016
            LMConnector targetConnector = null;
4017
            double[] resultPoint = null;
4018
            List<double[]> targetVertices = null;
4019

    
4020
            // Vertices 포인트에 제일 가까운곳
4021
            foreach (var item in vertices)
4022
            {
4023
                List<double[]> points = item.Value;
4024
                for (int i = 0; i < points.Count; i++)
4025
                {
4026
                    double[] point = points[i];
4027
                    double tempX = point[0];
4028
                    double tempY = point[1];
4029

    
4030
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4031
                    if (length >= distance)
4032
                    {
4033
                        targetConnector = item.Key;
4034
                        length = distance;
4035
                        resultPoint = point;
4036
                        targetVertices = item.Value;
4037
                    }
4038
                }
4039
            }
4040

    
4041
            // Vertices Cross에 제일 가까운곳
4042
            foreach (var item in vertices)
4043
            {
4044
                List<double[]> points = item.Value;
4045
                for (int i = 0; i < points.Count - 1; i++)
4046
                {
4047
                    double[] point1 = points[i];
4048
                    double[] point2 = points[i + 1];
4049

    
4050
                    double maxLineX = Math.Max(point1[0], point2[0]);
4051
                    double minLineX = Math.Min(point1[0], point2[0]);
4052
                    double maxLineY = Math.Max(point1[1], point2[1]);
4053
                    double minLineY = Math.Min(point1[1], point2[1]);
4054

    
4055
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4056

    
4057
                    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]);
4058
                    if (crossingPoint != null)
4059
                    {
4060
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4061
                        if (length >= distance)
4062
                        {
4063
                            if (slope == SlopeType.Slope &&
4064
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4065
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4066
                            {
4067
                                targetConnector = item.Key;
4068
                                length = distance;
4069
                                resultPoint = crossingPoint;
4070
                                targetVertices = item.Value;
4071
                            }
4072
                            else if (slope == SlopeType.HORIZONTAL &&
4073
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4074
                            {
4075
                                targetConnector = item.Key;
4076
                                length = distance;
4077
                                resultPoint = crossingPoint;
4078
                                targetVertices = item.Value;
4079
                            }
4080
                            else if (slope == SlopeType.VERTICAL &&
4081
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4082
                            {
4083
                                targetConnector = item.Key;
4084
                                length = distance;
4085
                                resultPoint = crossingPoint;
4086
                                targetVertices = item.Value;
4087
                            }
4088
                        }
4089
                    }
4090
                }
4091
            }
4092

    
4093
            foreach (var item in vertices)
4094
                if (item.Key != null && item.Key != targetConnector)
4095
                    ReleaseCOMObjects(item.Key);
4096

    
4097
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4098
            {
4099
                double tempResultX = resultPoint[0];
4100
                double tempResultY = resultPoint[1];
4101
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4102

    
4103
                GridSetting gridSetting = GridSetting.GetInstance();
4104

    
4105
                for (int i = 0; i < targetVertices.Count; i++)
4106
                {
4107
                    double[] point = targetVertices[i];
4108
                    double tempX = targetVertices[i][0];
4109
                    double tempY = targetVertices[i][1];
4110
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4111
                    if (tempX == tempResultX && tempY == tempResultY)
4112
                    {
4113
                        if (i == 0)
4114
                        {
4115
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4116
                            bool containZeroLength = false;
4117
                            if (connSymbol != null)
4118
                            {
4119
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4120
                                {
4121
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4122
                                        containZeroLength = true;
4123
                                }
4124
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4125
                                {
4126
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4127
                                        containZeroLength = true;
4128
                                }
4129
                            }
4130

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

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

    
4166
                                if (bCalcY)
4167
                                {
4168
                                    double nextY = targetVertices[i + 1][1];
4169
                                    double newY = 0;
4170
                                    if (nextY > tempY)
4171
                                    {
4172
                                        newY = tempY + gridSetting.Length;
4173
                                        if (newY > nextY)
4174
                                            newY = (point[1] + nextY) / 2;
4175
                                    }
4176
                                    else
4177
                                    {
4178
                                        newY = tempY - gridSetting.Length;
4179
                                        if (newY < nextY)
4180
                                            newY = (point[1] + nextY) / 2;
4181
                                    }
4182
                                    resultPoint = new double[] { resultPoint[0], newY };
4183
                                }
4184
                            }
4185
                        }
4186
                        else if (i == targetVertices.Count - 1)
4187
                        {
4188
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4189
                            bool containZeroLength = false;
4190
                            if (connSymbol != null)
4191
                            {
4192
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4193
                                {
4194
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4195
                                        containZeroLength = true;
4196
                                }
4197
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4198
                                {
4199
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4200
                                        containZeroLength = true;
4201
                                }
4202
                            }
4203

    
4204
                            if (connSymbol == null ||
4205
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4206
                                containZeroLength)
4207
                            {
4208
                                bool bCalcX = false;
4209
                                bool bCalcY = false;
4210
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4211
                                    bCalcX = true;
4212
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4213
                                    bCalcY = true;
4214
                                else
4215
                                {
4216
                                    bCalcX = true;
4217
                                    bCalcY = true;
4218
                                }
4219

    
4220
                                if (bCalcX)
4221
                                {
4222
                                    double nextX = targetVertices[i - 1][0];
4223
                                    double newX = 0;
4224
                                    if (nextX > tempX)
4225
                                    {
4226
                                        newX = tempX + gridSetting.Length;
4227
                                        if (newX > nextX)
4228
                                            newX = (point[0] + nextX) / 2;
4229
                                    }
4230
                                    else
4231
                                    {
4232
                                        newX = tempX - gridSetting.Length;
4233
                                        if (newX < nextX)
4234
                                            newX = (point[0] + nextX) / 2;
4235
                                    }
4236
                                    resultPoint = new double[] { newX, resultPoint[1] };
4237
                                }
4238

    
4239
                                if (bCalcY)
4240
                                {
4241
                                    double nextY = targetVertices[i - 1][1];
4242
                                    double newY = 0;
4243
                                    if (nextY > tempY)
4244
                                    {
4245
                                        newY = tempY + gridSetting.Length;
4246
                                        if (newY > nextY)
4247
                                            newY = (point[1] + nextY) / 2;
4248
                                    }
4249
                                    else
4250
                                    {
4251
                                        newY = tempY - gridSetting.Length;
4252
                                        if (newY < nextY)
4253
                                            newY = (point[1] + nextY) / 2;
4254
                                    }
4255
                                    resultPoint = new double[] { resultPoint[0], newY };
4256
                                }
4257
                            }
4258
                        }
4259
                        break;
4260
                    }
4261
                }
4262
            }
4263

    
4264
            x = resultPoint[0];
4265
            y = resultPoint[1];
4266

    
4267
            return targetConnector;
4268
        }
4269

    
4270
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4271
        {
4272
            LMConnector result = null;
4273
            List<LMConnector> connectors = new List<LMConnector>();
4274
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4275

    
4276
            if (modelItem != null)
4277
            {
4278
                foreach (LMRepresentation rep in modelItem.Representations)
4279
                {
4280
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4281
                        connectors.Add(dataSource.GetConnector(rep.Id));
4282
                }
4283

    
4284
                ReleaseCOMObjects(modelItem);
4285
            }
4286

    
4287
            if (connectors.Count == 1)
4288
                result = connectors[0];
4289
            else
4290
                foreach (var item in connectors)
4291
                    ReleaseCOMObjects(item);
4292

    
4293
            return result;
4294
        }
4295

    
4296
        private LMConnector GetLMConnectorFirst(string modelItemID)
4297
        {
4298
            LMConnector result = null;
4299
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4300

    
4301
            if (modelItem != null)
4302
            {
4303
                foreach (LMRepresentation rep in modelItem.Representations)
4304
                {
4305
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4306
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4307
                    {
4308
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4309
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4310
                        {
4311
                            result = connector;
4312
                            break;
4313
                        }
4314
                        else
4315
                        {
4316
                            ReleaseCOMObjects(connector);
4317
                            connector = null;
4318
                        }
4319
                    }
4320
                }
4321
                ReleaseCOMObjects(modelItem);
4322
                modelItem = null;
4323
            }
4324

    
4325
            return result;
4326
        }
4327

    
4328
        private int GetConnectorCount(string modelItemID)
4329
        {
4330
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4331
            int result = 0;
4332
            if (modelItem != null)
4333
            {
4334
                foreach (LMRepresentation rep in modelItem.Representations)
4335
                {
4336
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4337
                        result++;
4338
                    ReleaseCOMObjects(rep);
4339
                }
4340
                ReleaseCOMObjects(modelItem);
4341
            }
4342

    
4343
            return result;
4344
        }
4345

    
4346
        public List<string> GetRepresentations(string modelItemID)
4347
        {
4348
            List<string> result = new List<string>(); ;
4349
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4350
            if (modelItem != null)
4351
            {
4352
                foreach (LMRepresentation rep in modelItem.Representations)
4353
                {
4354
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4355
                        result.Add(rep.Id);
4356
                }
4357
                ReleaseCOMObjects(modelItem);
4358
            }
4359

    
4360
            return result;
4361
        }
4362

    
4363
        private void LineNumberModeling(LineNumber lineNumber)
4364
        {
4365
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4366
            if (line != null)
4367
            {
4368
                double x = 0;
4369
                double y = 0;
4370
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4371

    
4372
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4373
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4374
                if (connectedLMConnector != null)
4375
                {
4376
                    Array points = new double[] { 0, x, y };
4377
                    lineNumber.SPPID.SPPID_X = x;
4378
                    lineNumber.SPPID.SPPID_Y = y;
4379
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4380

    
4381
                    if (_LmLabelPresist != null)
4382
                    {
4383
                        _LmLabelPresist.Commit();
4384
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4385
                        ReleaseCOMObjects(_LmLabelPresist);
4386
                    }
4387
                }
4388

    
4389
                foreach (var item in connectorVertices)
4390
                    ReleaseCOMObjects(item.Key);
4391
            }
4392
        }
4393
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4394
        {
4395
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4396
            if (line == null || line.SPPID.Vertices == null)
4397
                return;
4398

    
4399
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4400
            {
4401
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4402
                if (removeLabel != null)
4403
                {
4404
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4405
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4406

    
4407
                    GridSetting gridSetting = GridSetting.GetInstance();
4408
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4409

    
4410
                    double[] labelRange = null;
4411
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4412
                    List<double[]> vertices = GetConnectorVertices(connector);
4413

    
4414
                    double[] resultStart = null;
4415
                    double[] resultEnd = null;
4416
                    double distance = double.MaxValue;
4417
                    for (int i = 0; i < vertices.Count - 1; i++)
4418
                    {
4419
                        double[] startPoint = vertices[i];
4420
                        double[] endPoint = vertices[i + 1];
4421
                        foreach (var item in line.SPPID.Vertices)
4422
                        {
4423
                            double[] lineStartPoint = item[0];
4424
                            double[] lineEndPoint = item[item.Count - 1];
4425

    
4426
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4427
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4428
                            if (tempDistance < distance)
4429
                            {
4430
                                distance = tempDistance;
4431
                                resultStart = startPoint;
4432
                                resultEnd = endPoint;
4433
                            }
4434
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4435
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4436
                            if (tempDistance < distance)
4437
                            {
4438
                                distance = tempDistance;
4439
                                resultStart = startPoint;
4440
                                resultEnd = endPoint;
4441
                            }
4442
                        }
4443
                    }
4444

    
4445
                    if (resultStart != null && resultEnd != null)
4446
                    {
4447
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4448
                        double lineStartX = 0;
4449
                        double lineStartY = 0;
4450
                        double lineEndX = 0;
4451
                        double lineEndY = 0;
4452
                        double lineNumberX = 0;
4453
                        double lineNumberY = 0;
4454
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4455
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4456

    
4457
                        double lineX = (lineStartX + lineEndX) / 2;
4458
                        double lineY = (lineStartY + lineEndY) / 2;
4459
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4460
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4461

    
4462
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4463
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4464
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4465
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4466

    
4467
                        double offsetX = 0;
4468
                        double offsetY = 0;
4469
                        if (slope == SlopeType.HORIZONTAL)
4470
                        {
4471
                            // Line Number 아래
4472
                            if (lineY < lineNumberY)
4473
                            {
4474
                                offsetX = labelCenterX - SPPIDCenterX;
4475
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4476
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4477
                            }
4478
                            // Line Number 위
4479
                            else
4480
                            {
4481
                                offsetX = labelCenterX - SPPIDCenterX;
4482
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4483
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4484
                            }
4485
                        }
4486
                        else if (slope == SlopeType.VERTICAL)
4487
                        {
4488
                            // Line Number 오르쪽
4489
                            if (lineX < lineNumberX)
4490
                            {
4491
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4492
                                offsetY = labelCenterY - SPPIDCenterY;
4493
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4494
                            }
4495
                            // Line Number 왼쪽
4496
                            else
4497
                            {
4498
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4499
                                offsetY = labelCenterY - SPPIDCenterY;
4500
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4501
                            }
4502
                        }
4503

    
4504
                        if (offsetY != 0 || offsetY != 0)
4505
                        {
4506
                            if (connector.ConnectItem1SymbolObject != null &&
4507
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4508
                            {
4509
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4510

    
4511
                                double x1, y1, x2, y2, originX, originY;
4512
                                symbol.Range(out x1, out y1, out x2, out y2);
4513
                                symbol.GetOrigin(out originX, out originY);
4514
                                if (originX < lineNumber.SPPID.SPPID_X)
4515
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4516
                                else
4517
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4518
                            }
4519
                            else if (connector.ConnectItem2SymbolObject != null &&
4520
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4521
                            {
4522
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4523

    
4524
                                double x1, y1, x2, y2, originX, originY;
4525
                                symbol.Range(out x1, out y1, out x2, out y2);
4526
                                symbol.GetOrigin(out originX, out originY);
4527
                                if (originX < lineNumber.SPPID.SPPID_X)
4528
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4529
                                else
4530
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4531
                            }
4532

    
4533
                            radApp.ActiveSelectSet.RemoveAll();
4534
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
4535
                            if (dependency != null)
4536
                            {
4537
                                radApp.ActiveSelectSet.Add(dependency);
4538
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4539
                                transform.DefineByMove2d(-offsetX, -offsetY);
4540
                                radApp.ActiveSelectSet.Transform(transform, true);
4541
                                radApp.ActiveSelectSet.RemoveAll();
4542
                            }
4543
                        }
4544

    
4545
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4546
                        {
4547
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4548
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4549
                        }
4550
                    }
4551

    
4552

    
4553
                    ReleaseCOMObjects(connector);
4554
                    connector = null;
4555
                }
4556

    
4557
                ReleaseCOMObjects(removeLabel);
4558
                removeLabel = null;
4559
            }
4560
        }
4561
        /// <summary>
4562
        /// Flow Mark Modeling
4563
        /// </summary>
4564
        /// <param name="line"></param>
4565
        private void FlowMarkModeling(Line line)
4566
        {
4567
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4568
            {
4569
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4570
                if (connector != null)
4571
                {
4572
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4573
                    List<double[]> vertices = GetConnectorVertices(connector);
4574
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4575
                    double[] point = vertices[vertices.Count - 1];
4576
                    Array array = new double[] { 0, point[0], point[1] };
4577
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4578
                    if (_LMLabelPersist != null)
4579
                    {
4580
                        _LMLabelPersist.Commit();
4581
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4582
                        ReleaseCOMObjects(_LMLabelPersist);
4583
                    }
4584
                }
4585
            }
4586
        }
4587

    
4588
        /// <summary>
4589
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4590
        /// </summary>
4591
        /// <param name="lineNumber"></param>
4592
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4593
        {
4594
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4595
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4596
            {
4597
                if (a.ATTRIBUTE == "Tag Seq No")
4598
                    return 1;
4599
                else if (b.ATTRIBUTE == "Tag Seq No")
4600
                    return -1;
4601

    
4602
                return 0;
4603
            }
4604

    
4605
            foreach (LineRun run in lineNumber.RUNS)
4606
            {
4607
                foreach (var item in run.RUNITEMS)
4608
                {
4609
                    if (item.GetType() == typeof(Symbol))
4610
                    {
4611
                        Symbol symbol = item as Symbol;
4612
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4613
                        if (_LMSymbol != null)
4614
                        {
4615
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4616

    
4617
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4618
                            {
4619
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4620
                                {
4621
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4622
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4623
                                    {
4624
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4625
                                        if (_LMAAttribute != null)
4626
                                        {
4627
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4628
                                                _LMAAttribute.set_Value(attribute.VALUE);
4629
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4630
                                                _LMAAttribute.set_Value(attribute.VALUE);
4631
                                        }
4632
                                    }
4633
                                }
4634
                                _LMModelItem.Commit();
4635
                            }
4636
                            if (_LMModelItem != null)
4637
                                ReleaseCOMObjects(_LMModelItem);
4638
                        }
4639
                        if (_LMSymbol != null)
4640
                            ReleaseCOMObjects(_LMSymbol);
4641
                    }
4642
                    else if (item.GetType() == typeof(Line))
4643
                    {
4644
                        Line line = item as Line;
4645
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4646
                        {
4647
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4648
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4649
                            {
4650
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4651
                                {
4652
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4653
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4654
                                    {
4655
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4656
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
4657
                                        {
4658
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
4659
                                            if (_FluidSystemAttribute != null)
4660
                                            {
4661
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
4662
                                                if (dt.Rows.Count == 1)
4663
                                                {
4664
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
4665
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
4666
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4667
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
4668
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4669

    
4670
                                                    if (_LMAAttribute != null)
4671
                                                    {
4672
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4673
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4674
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4675
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4676
                                                    }
4677
                                                }
4678
                                                if (dt != null)
4679
                                                    dt.Dispose();
4680
                                            }
4681
                                        }
4682
                                        else if (_LMAAttribute != null)
4683
                                        {
4684
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4685
                                                _LMAAttribute.set_Value(attribute.VALUE);
4686
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4687
                                                _LMAAttribute.set_Value(attribute.VALUE);
4688
                                        }
4689
                                    }
4690
                                }
4691
                                _LMModelItem.Commit();
4692
                            }
4693
                            if (_LMModelItem != null)
4694
                                ReleaseCOMObjects(_LMModelItem);
4695
                            endLine.Add(line.SPPID.ModelItemId);
4696
                        }
4697
                    }
4698
                }
4699
            }
4700
        }
4701

    
4702
        /// <summary>
4703
        /// Symbol Attribute 입력 메서드
4704
        /// </summary>
4705
        /// <param name="item"></param>
4706
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4707
        {
4708
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4709
            string sRep = null;
4710
            string sModelID = null;
4711
            if (targetItem.GetType() == typeof(Symbol))
4712
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4713
            else if (targetItem.GetType() == typeof(Equipment))
4714
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4715
            else if (targetItem.GetType() == typeof(Line))
4716
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
4717
            
4718
            if (!string.IsNullOrEmpty(sRep))
4719
            {
4720
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4721
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
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
                            {
4734
                                _Attribute.set_Value(item.VALUE);
4735
                                // OPC 일경우 Attribute 저장
4736
                                if (targetItem.GetType() == typeof(Symbol))
4737
                                {
4738
                                    Symbol symbol = targetItem as Symbol;
4739
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4740
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4741
                                }
4742
                            }
4743
                        }
4744
                        else
4745
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
4746
                    }
4747
                }
4748
                _LMModelItem.Commit();
4749

    
4750
                ReleaseCOMObjects(_Attributes);
4751
                ReleaseCOMObjects(_LMModelItem);
4752
                ReleaseCOMObjects(_LMSymbol);
4753
            }
4754
            else if (!string.IsNullOrEmpty(sModelID))
4755
            {
4756
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
4757
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4758

    
4759
                foreach (var item in targetAttributes)
4760
                {
4761
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4762
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4763
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
4764
                    {
4765
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
4766
                        if (_FluidSystemAttribute != null)
4767
                        {
4768
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
4769
                            if (dt.Rows.Count == 1)
4770
                            {
4771
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
4772
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
4773
                                    _FluidSystemAttribute.set_Value(fluidSystem);
4774
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
4775
                                    _FluidSystemAttribute.set_Value(fluidSystem);
4776

    
4777
                                if (_LMAAttribute != null)
4778
                                {
4779
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4780
                                        _LMAAttribute.set_Value(item.VALUE);
4781
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
4782
                                        _LMAAttribute.set_Value(item.VALUE);
4783
                                }
4784
                            }
4785
                            if (dt != null)
4786
                                dt.Dispose();
4787
                        }
4788
                    }
4789
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4790
                    {
4791
                        if (!mapping.IsText)
4792
                        {
4793
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4794
                            if (_Attribute != null)
4795
                                _Attribute.set_Value(item.VALUE);
4796
                        }
4797
                    }
4798
                }
4799
                _LMModelItem.Commit();
4800

    
4801
                ReleaseCOMObjects(_Attributes);
4802
                ReleaseCOMObjects(_LMModelItem);
4803
            }
4804
        }
4805

    
4806
        /// <summary>
4807
        /// Input SpecBreak Attribute
4808
        /// </summary>
4809
        /// <param name="specBreak"></param>
4810
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4811
        {
4812
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4813
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4814

    
4815
            if (upStreamObj != null &&
4816
                downStreamObj != null)
4817
            {
4818
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4819

    
4820
                if (targetLMConnector != null)
4821
                {
4822
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4823
                    {
4824
                        string symbolPath = _LMLabelPersist.get_FileName();
4825
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4826
                        if (mapping != null)
4827
                        {
4828
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4829
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4830
                            {
4831
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4832
                                if (values.Length == 2)
4833
                                {
4834
                                    string upStreamValue = values[0];
4835
                                    string downStreamValue = values[1];
4836

    
4837
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4838
                                }
4839
                            }
4840
                        }
4841
                    }
4842

    
4843
                    ReleaseCOMObjects(targetLMConnector);
4844
                }
4845
            }
4846

    
4847

    
4848
            #region 내부에서만 쓰는 메서드
4849
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4850
            {
4851
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4852
                Line upStreamLine = _upStreamObj as Line;
4853
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4854
                Line downStreamLine = _downStreamObj as Line;
4855
                // 둘다 Line일 경우
4856
                if (upStreamLine != null && downStreamLine != null)
4857
                {
4858
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4859
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4860
                }
4861
                // 둘다 Symbol일 경우
4862
                else if (upStreamSymbol != null && downStreamSymbol != null)
4863
                {
4864
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4865
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4866
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4867

    
4868
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4869
                    {
4870
                        if (connector.get_ItemStatus() != "Active")
4871
                            continue;
4872

    
4873
                        if (connector.Id != zeroLenthConnector.Id)
4874
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4875
                    }
4876

    
4877
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4878
                    {
4879
                        if (connector.get_ItemStatus() != "Active")
4880
                            continue;
4881

    
4882
                        if (connector.Id != zeroLenthConnector.Id)
4883
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4884
                    }
4885

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

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

    
4895
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4896
                    {
4897
                        if (connector.get_ItemStatus() != "Active")
4898
                            continue;
4899

    
4900
                        if (connector.Id != zeroLenthConnector.Id)
4901
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4902
                    }
4903

    
4904
                    ReleaseCOMObjects(zeroLenthConnector);
4905
                    ReleaseCOMObjects(upStreamLMSymbol);
4906
                    ReleaseCOMObjects(downStreamLMSymbol);
4907
                }
4908
                else if (upStreamSymbol != null && downStreamLine != null)
4909
                {
4910
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4911
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4912
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4913

    
4914
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4915
                    {
4916
                        if (connector.get_ItemStatus() != "Active")
4917
                            continue;
4918

    
4919
                        if (connector.Id == zeroLenthConnector.Id)
4920
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4921
                    }
4922

    
4923
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4924
                    {
4925
                        if (connector.get_ItemStatus() != "Active")
4926
                            continue;
4927

    
4928
                        if (connector.Id == zeroLenthConnector.Id)
4929
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4930
                    }
4931

    
4932
                    ReleaseCOMObjects(zeroLenthConnector);
4933
                    ReleaseCOMObjects(upStreamLMSymbol);
4934
                }
4935
                else if (upStreamLine != null && downStreamSymbol != null)
4936
                {
4937
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4938
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4939
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4940

    
4941
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4942
                    {
4943
                        if (connector.get_ItemStatus() != "Active")
4944
                            continue;
4945

    
4946
                        if (connector.Id == zeroLenthConnector.Id)
4947
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4948
                    }
4949

    
4950
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4951
                    {
4952
                        if (connector.get_ItemStatus() != "Active")
4953
                            continue;
4954

    
4955
                        if (connector.Id == zeroLenthConnector.Id)
4956
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4957
                    }
4958

    
4959
                    ReleaseCOMObjects(zeroLenthConnector);
4960
                    ReleaseCOMObjects(downStreamLMSymbol);
4961
                }
4962
            }
4963

    
4964
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4965
            {
4966
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4967
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4968
                {
4969
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4970
                    if (_LMAAttribute != null)
4971
                    {
4972
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4973
                            _LMAAttribute.set_Value(value);
4974
                        else if (_LMAAttribute.get_Value() != value)
4975
                            _LMAAttribute.set_Value(value);
4976
                    }
4977

    
4978
                    _LMModelItem.Commit();
4979
                }
4980
                if (_LMModelItem != null)
4981
                    ReleaseCOMObjects(_LMModelItem);
4982
            }
4983

    
4984
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4985
            {
4986
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4987
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4988
                {
4989
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4990
                    if (_LMAAttribute != null)
4991
                    {
4992
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4993
                            _LMAAttribute.set_Value(value);
4994
                        else if (_LMAAttribute.get_Value() != value)
4995
                            _LMAAttribute.set_Value(value);
4996
                    }
4997

    
4998
                    _LMModelItem.Commit();
4999
                }
5000
                if (_LMModelItem != null)
5001
                    ReleaseCOMObjects(_LMModelItem);
5002
            }
5003
            #endregion
5004
        }
5005

    
5006
        private void InputEndBreakAttribute(EndBreak endBreak)
5007
        {
5008
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5009
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5010

    
5011
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
5012
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
5013
            {
5014
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
5015
                if (labelPersist != null)
5016
                {
5017
                    LMRepresentation representation = labelPersist.RepresentationObject;
5018
                    if (representation != null)
5019
                    {
5020
                        LMConnector connector = dataSource.GetConnector(representation.Id);
5021
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
5022
                        string modelItemID = connector.ModelItemID;
5023
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
5024
                        {
5025
                            List<string> modelItemIDs = new List<string>();
5026
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5027
                            {
5028
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
5029
                                foreach (LMConnector item in symbol.Connect1Connectors)
5030
                                {
5031
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5032
                                        modelItemIDs.Add(item.ModelItemID);
5033
                                    ReleaseCOMObjects(item);
5034
                                }
5035
                                foreach (LMConnector item in symbol.Connect2Connectors)
5036
                                {
5037
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5038
                                        modelItemIDs.Add(item.ModelItemID);
5039
                                    ReleaseCOMObjects(item);
5040
                                }
5041
                                ReleaseCOMObjects(symbol);
5042
                                symbol = null;
5043
                            }
5044
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5045
                            {
5046
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
5047
                                foreach (LMConnector item in symbol.Connect1Connectors)
5048
                                {
5049
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5050
                                        modelItemIDs.Add(item.ModelItemID);
5051
                                    ReleaseCOMObjects(item);
5052
                                }
5053
                                foreach (LMConnector item in symbol.Connect2Connectors)
5054
                                {
5055
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5056
                                        modelItemIDs.Add(item.ModelItemID);
5057
                                    ReleaseCOMObjects(item);
5058
                                }
5059
                                ReleaseCOMObjects(symbol);
5060
                                symbol = null;
5061
                            }
5062

    
5063
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5064
                            if (modelItemIDs.Count == 1)
5065
                            {
5066
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5067
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5068
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5069
                                {
5070
                                    bool result = false;
5071
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5072
                                    {
5073
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5074
                                            result = true;
5075
                                        ReleaseCOMObjects(loop);
5076
                                    }
5077

    
5078
                                    if (result)
5079
                                    {
5080
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5081
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5082
                                        ZeroLengthModelItem.Commit();
5083
                                    }
5084
                                    else
5085
                                    {
5086
                                        List<string> loopModelItems = new List<string>();
5087
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5088
                                        {
5089
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5090
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5091
                                            {
5092
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5093
                                                    loopModelItems.Add(loop.ModelItemID);
5094
                                                ReleaseCOMObjects(loop);
5095
                                            }
5096
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5097
                                            {
5098
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5099
                                                    loopModelItems.Add(loop.ModelItemID);
5100
                                                ReleaseCOMObjects(loop);
5101
                                            }
5102
                                            ReleaseCOMObjects(_symbol);
5103
                                            _symbol = null;
5104
                                        }
5105
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5106
                                        {
5107
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5108
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5109
                                            {
5110
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5111
                                                    loopModelItems.Add(loop.ModelItemID);
5112
                                                ReleaseCOMObjects(loop);
5113
                                            }
5114
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5115
                                            {
5116
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5117
                                                    loopModelItems.Add(loop.ModelItemID);
5118
                                                ReleaseCOMObjects(loop);
5119
                                            }
5120
                                            ReleaseCOMObjects(_symbol);
5121
                                            _symbol = null;
5122
                                        }
5123

    
5124
                                        loopModelItems = loopModelItems.Distinct().ToList();
5125
                                        if (loopModelItems.Count == 1)
5126
                                        {
5127
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5128
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5129
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5130
                                            modelItem.Commit();
5131
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5132
                                            ZeroLengthModelItem.Commit();
5133

    
5134
                                            ReleaseCOMObjects(loopModelItem);
5135
                                            loopModelItem = null;
5136
                                        }
5137
                                    }
5138
                                }
5139
                                else
5140
                                {
5141
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5142
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5143
                                    ZeroLengthModelItem.Commit();
5144
                                }
5145
                                ReleaseCOMObjects(modelItem);
5146
                                modelItem = null;
5147
                                ReleaseCOMObjects(onlyOne);
5148
                                onlyOne = null;
5149
                            }
5150
                        }
5151
                        ReleaseCOMObjects(connector);
5152
                        connector = null;
5153
                        ReleaseCOMObjects(ZeroLengthModelItem);
5154
                        ZeroLengthModelItem = null;
5155
                    }
5156
                    ReleaseCOMObjects(representation);
5157
                    representation = null;
5158
                }
5159
                ReleaseCOMObjects(labelPersist);
5160
                labelPersist = null;
5161
            }
5162
        }
5163

    
5164
        /// <summary>
5165
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5166
        /// </summary>
5167
        /// <param name="text"></param>
5168
        private void NormalTextModeling(Text text)
5169
        {
5170
            LMSymbol _LMSymbol = null;
5171

    
5172
            LMItemNote _LMItemNote = null;
5173
            LMAAttribute _LMAAttribute = null;
5174

    
5175
            double x = 0;
5176
            double y = 0;
5177
            double angle = text.ANGLE;
5178
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5179

    
5180
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5181
            text.SPPID.SPPID_X = x;
5182
            text.SPPID.SPPID_Y = y;
5183

    
5184
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5185
            if (_LMSymbol != null)
5186
            {
5187
                _LMSymbol.Commit();
5188
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5189
                if (_LMItemNote != null)
5190
                {
5191
                    _LMItemNote.Commit();
5192
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5193
                    if (_LMAAttribute != null)
5194
                    {
5195
                        _LMAAttribute.set_Value(text.VALUE);
5196
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5197
                        _LMItemNote.Commit();
5198

    
5199

    
5200
                        double[] range = null;
5201
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5202
                        {
5203
                            double[] temp = null;
5204
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5205
                            if (temp != null)
5206
                            {
5207
                                if (range == null)
5208
                                    range = temp;
5209
                                else
5210
                                {
5211
                                    range = new double[] {
5212
                                            Math.Min(range[0], temp[0]),
5213
                                            Math.Min(range[1], temp[1]),
5214
                                            Math.Max(range[2], temp[2]),
5215
                                            Math.Max(range[3], temp[3])
5216
                                        };
5217
                                }
5218
                            }
5219
                        }
5220
                        text.SPPID.Range = range;
5221

    
5222
                        if (_LMAAttribute != null)
5223
                            ReleaseCOMObjects(_LMAAttribute);
5224
                        if (_LMItemNote != null)
5225
                            ReleaseCOMObjects(_LMItemNote);
5226
                    }
5227

    
5228
                    TextCorrectModeling(text);
5229
                }
5230
            }
5231
            if (_LMSymbol != null)
5232
                ReleaseCOMObjects(_LMSymbol);
5233
        }
5234

    
5235
        private void DefaultTextModeling(string value, double x, double y)
5236
        {
5237
            LMSymbol _LMSymbol = null;
5238

    
5239
            LMItemNote _LMItemNote = null;
5240
            LMAAttribute _LMAAttribute = null;
5241

    
5242
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5243
            if (_LMSymbol != null)
5244
            {
5245
                _LMSymbol.Commit();
5246
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5247
                if (_LMItemNote != null)
5248
                {
5249
                    _LMItemNote.Commit();
5250
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5251
                    if (_LMAAttribute != null)
5252
                    {
5253
                        _LMAAttribute.set_Value(value);
5254
                        _LMItemNote.Commit();
5255

    
5256
                        if (_LMAAttribute != null)
5257
                            ReleaseCOMObjects(_LMAAttribute);
5258
                        if (_LMItemNote != null)
5259
                            ReleaseCOMObjects(_LMItemNote);
5260
                    }
5261
                }
5262
            }
5263
            if (_LMSymbol != null)
5264
                ReleaseCOMObjects(_LMSymbol);
5265
        }
5266

    
5267
        private void AssociationTextModeling(Text text)
5268
        {
5269
            LMSymbol _LMSymbol = null;
5270
            LMConnector connectedLMConnector = null;
5271
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5272
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
5273
            {
5274
                Symbol symbol = owner as Symbol;
5275
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5276
                if (_LMSymbol != null)
5277
                {
5278
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5279
                    {
5280
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5281
                        {
5282
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5283

    
5284
                            if (mapping != null)
5285
                            {
5286
                                double x = 0;
5287
                                double y = 0;
5288

    
5289
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5290
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5291
                                Array array = new double[] { 0, x, y };
5292
                                text.SPPID.SPPID_X = x;
5293
                                text.SPPID.SPPID_Y = y;
5294
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5295
                                if (_LMLabelPersist != null)
5296
                                {
5297
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5298
                                    _LMLabelPersist.Commit();
5299
                                    ReleaseCOMObjects(_LMLabelPersist);
5300
                                }
5301
                            }
5302
                        }
5303
                    }
5304
                }
5305
            }
5306
            else if (owner != null && owner.GetType() == typeof(Line))
5307
            {
5308
                Line line = owner as Line;
5309
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5310
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5311

    
5312
                if (connectedLMConnector != null)
5313
                {
5314
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5315
                    {
5316
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5317
                        {
5318
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5319

    
5320
                            if (mapping != null)
5321
                            {
5322
                                double x = 0;
5323
                                double y = 0;
5324
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5325
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5326
                                Array array = new double[] { 0, x, y };
5327

    
5328
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5329
                                if (_LMLabelPersist != null)
5330
                                {
5331
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5332
                                    _LMLabelPersist.Commit();
5333

    
5334
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5335
                                    if (dependency != null)
5336
                                    {
5337
                                        radApp.ActiveSelectSet.RemoveAll();
5338
                                        radApp.ActiveSelectSet.Add(dependency);
5339
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
5340
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5341
                                        radApp.ActiveSelectSet.Transform(transform, true);
5342
                                        radApp.ActiveSelectSet.RemoveAll();
5343
                                    }
5344

    
5345
                                    ReleaseCOMObjects(_LMLabelPersist);
5346
                                }
5347
                            }
5348
                        }
5349
                    }
5350
                }
5351
            }
5352
            if (_LMSymbol != null)
5353
                ReleaseCOMObjects(_LMSymbol);
5354
        }
5355

    
5356
        private void TextCorrectModeling(Text text)
5357
        {
5358
            if (text.SPPID.Range == null)
5359
                return;
5360

    
5361
            bool needRemodeling = false;
5362
            bool loop = true;
5363
            GridSetting gridSetting = GridSetting.GetInstance();
5364
            while (loop)
5365
            {
5366
                loop = false;
5367
                foreach (var overlapText in document.TEXTINFOS)
5368
                {
5369
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5370
                        continue;
5371

    
5372
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5373
                    {
5374
                        double percentX = 0;
5375
                        double percentY = 0;
5376
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5377
                        {
5378
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5379
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5380
                        }
5381
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5382
                        {
5383
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5384
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5385
                        }
5386

    
5387
                        double tempX = 0;
5388
                        double tempY = 0;
5389
                        bool overlapX = false;
5390
                        bool overlapY = false;
5391
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5392
                        if (percentX >= percentY)
5393
                        {
5394
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5395
                            double move = gridSetting.Length * count;
5396
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5397
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5398
                            needRemodeling = true;
5399
                            loop = true;
5400
                        }
5401
                        else
5402
                        {
5403
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5404
                            double move = gridSetting.Length * count;
5405
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5406
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5407
                            needRemodeling = true;
5408
                            loop = true;
5409
                        }
5410
                    }
5411
                }
5412
            }
5413
            
5414

    
5415
            if (needRemodeling)
5416
            {
5417
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5418
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5419
                text.SPPID.RepresentationId = null;
5420

    
5421
                LMItemNote _LMItemNote = null;
5422
                LMAAttribute _LMAAttribute = null;
5423
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5424
                if (_LMSymbol != null)
5425
                {
5426
                    _LMSymbol.Commit();
5427
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5428
                    if (_LMItemNote != null)
5429
                    {
5430
                        _LMItemNote.Commit();
5431
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5432
                        if (_LMAAttribute != null)
5433
                        {
5434
                            _LMAAttribute.set_Value(text.VALUE);
5435
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5436
                            _LMItemNote.Commit();
5437

    
5438
                            ReleaseCOMObjects(_LMAAttribute);
5439
                            ReleaseCOMObjects(_LMItemNote);
5440
                        }
5441
                    }
5442
                }
5443

    
5444
                ReleaseCOMObjects(symbol);
5445
                symbol = null;
5446
                ReleaseCOMObjects(_LMItemNote);
5447
                _LMItemNote = null;
5448
                ReleaseCOMObjects(_LMAAttribute);
5449
                _LMAAttribute = null;
5450
                ReleaseCOMObjects(_LMSymbol);
5451
                _LMSymbol = null;
5452
            }
5453
        }
5454

    
5455
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5456
        {
5457
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5458
            {
5459
                List<Text> allTexts = new List<Text>();
5460
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5461
                LMRepresentation representation = targetLabel.RepresentationObject;
5462
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5463
                if (targetLabel.RepresentationObject != null && symbol != null)
5464
                {
5465
                    double[] symbolRange = null;
5466
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5467
                    if (symbolRange != null)
5468
                    {
5469
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5470
                        {
5471
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5472
                            if (findText != null)
5473
                            {
5474
                                double[] range = null;
5475
                                GetSPPIDSymbolRange(labelPersist, ref range);
5476
                                findText.SPPID.Range = range;
5477
                                allTexts.Add(findText);
5478
                            }
5479

    
5480
                            ReleaseCOMObjects(labelPersist);
5481
                        }
5482

    
5483
                        if (allTexts.Count > 0)
5484
                        {
5485
                            #region Sort Text By Y
5486
                            allTexts.Sort(SortTextByY);
5487
                            int SortTextByY(Text a, Text b)
5488
                            {
5489
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5490
                            }
5491
                            #endregion
5492

    
5493
                            #region 정렬하기전 방향
5494
                            List<Text> left = new List<Text>();
5495
                            List<Text> down = new List<Text>();
5496
                            List<Text> right = new List<Text>();
5497
                            List<Text> up = new List<Text>();
5498
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5499
                            foreach (var loopText in allTexts)
5500
                            {
5501
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5502
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5503
                                double originX = 0;
5504
                                double originY = 0;
5505
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5506
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5507

    
5508
                                if (angle < 45)
5509
                                {
5510
                                    // Text 오른쪽
5511
                                    if (textCenterX > originX)
5512
                                        right.Add(loopText);
5513
                                    // Text 왼쪽
5514
                                    else
5515
                                        left.Add(loopText); 
5516
                                }
5517
                                else
5518
                                {
5519
                                    // Text 아래쪽
5520
                                    if (textCenterY > originY)
5521
                                        down.Add(loopText);
5522
                                    // Text 위쪽
5523
                                    else
5524
                                        up.Add(loopText);
5525
                                }
5526
                            }
5527
                            
5528
                            #endregion
5529

    
5530
                            foreach (var texts in sortTexts)
5531
                            {
5532
                                if (texts.Count == 0 )
5533
                                    continue;
5534
                                
5535
                                #region 첫번째 Text로 기준 맞춤
5536
                                for (int i = 0; i < texts.Count; i++)
5537
                                {
5538
                                    if (i != 0)
5539
                                    {
5540
                                        Text currentText = texts[i];
5541
                                        Text prevText = texts[i - 1];
5542
                                        double minY = prevText.SPPID.Range[1];
5543
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5544
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5545
                                        double _gapX = centerX - centerPrevX;
5546
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5547
                                        MoveText(currentText, _gapX, _gapY);
5548
                                    }
5549
                                }
5550
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5551
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5552
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5553
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5554
                                rangeMinX.Sort();
5555
                                rangeMinY.Sort();
5556
                                rangeMaxX.Sort();
5557
                                rangeMaxY.Sort();
5558
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5559
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5560
                                #endregion
5561
                                #region 정렬
5562
                                Text correctBySymbol = texts[0];
5563
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5564
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5565
                                double originX = 0;
5566
                                double originY = 0;
5567
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5568
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5569
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5570
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5571

    
5572
                                double gapX = 0;
5573
                                double gapY = 0;
5574
                                if (angle < 45)
5575
                                {
5576
                                    // Text 오른쪽
5577
                                    if (textCenterX > originX)
5578
                                    {
5579
                                        gapX = rangeMinX[0] - symbolRange[2];
5580
                                        gapY = allTextCenterY - symbolCenterY;
5581
                                    }
5582
                                    // Text 왼쪽
5583
                                    else
5584
                                    {
5585
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5586
                                        gapY = allTextCenterY - symbolCenterY;
5587
                                    }
5588
                                }
5589
                                else
5590
                                {
5591
                                    // Text 아래쪽
5592
                                    if (textCenterY > originY)
5593
                                    {
5594
                                        gapX = allTextCenterX - symbolCenterX;
5595
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5596
                                    }
5597
                                    // Text 위쪽
5598
                                    else
5599
                                    {
5600
                                        gapX = allTextCenterX - symbolCenterX;
5601
                                        gapY = rangeMinY[0] - symbolRange[3];
5602
                                    }
5603
                                }
5604

    
5605
                                foreach (var item in texts)
5606
                                {
5607
                                    MoveText(item, gapX, gapY);
5608
                                    RemodelingAssociationText(item);
5609
                                }
5610
                                #endregion
5611
                            }
5612
                        }
5613
                    }
5614
                }
5615

    
5616
                void MoveText(Text moveText, double x, double y)
5617
                {
5618
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5619
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5620
                    moveText.SPPID.Range = new double[] {
5621
                        moveText.SPPID.Range[0] - x,
5622
                        moveText.SPPID.Range[1]- y,
5623
                        moveText.SPPID.Range[2]- x,
5624
                        moveText.SPPID.Range[3]- y
5625
                    };
5626
                }
5627

    
5628
                endTexts.AddRange(allTexts);
5629

    
5630
                ReleaseCOMObjects(targetLabel);
5631
                targetLabel = null;
5632
                ReleaseCOMObjects(representation);
5633
                representation = null;
5634
            }
5635
        }
5636

    
5637
        private void RemodelingAssociationText(Text text)
5638
        {
5639
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5640
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5641
            removeLabel.Commit();
5642
            ReleaseCOMObjects(removeLabel);
5643
            removeLabel = null;
5644

    
5645
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5646
            if (owner != null && owner.GetType() == typeof(Symbol))
5647
            {
5648
                Symbol symbol = owner as Symbol;
5649
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5650
                if (_LMSymbol != null)
5651
                {
5652
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5653
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5654
                    {
5655
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5656

    
5657
                        if (mapping != null)
5658
                        {
5659
                            double x = 0;
5660
                            double y = 0;
5661

    
5662
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5663
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5664
                            if (_LMLabelPersist != null)
5665
                            {
5666
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5667
                                _LMLabelPersist.Commit();
5668
                            }
5669
                            ReleaseCOMObjects(_LMLabelPersist);
5670
                            _LMLabelPersist = null;
5671
                        }
5672
                    }
5673
                }
5674
                ReleaseCOMObjects(_LMSymbol);
5675
                _LMSymbol = null;
5676
            }
5677
        }
5678

    
5679
        /// <summary>
5680
        /// Note Modeling
5681
        /// </summary>
5682
        /// <param name="note"></param>
5683
        private void NoteModeling(Note note, List<Note> correctList)
5684
        {
5685
            LMSymbol _LMSymbol = null;
5686
            LMItemNote _LMItemNote = null;
5687
            LMAAttribute _LMAAttribute = null;
5688

    
5689
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5690
            {
5691
                double x = 0;
5692
                double y = 0;
5693

    
5694
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5695
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5696
                note.SPPID.SPPID_X = x;
5697
                note.SPPID.SPPID_Y = y;
5698

    
5699
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5700
                if (_LMSymbol != null)
5701
                {
5702
                    _LMSymbol.Commit();
5703
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5704
                    if (_LMItemNote != null)
5705
                    {
5706
                        _LMItemNote.Commit();
5707
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5708
                        if (_LMAAttribute != null)
5709
                        {
5710
                            _LMAAttribute.set_Value(note.VALUE);
5711
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5712

    
5713
                            double[] range = null;
5714
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5715
                            {
5716
                                double[] temp = null;
5717
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5718
                                if (temp != null)
5719
                                {
5720
                                    if (range == null)
5721
                                        range = temp;
5722
                                    else
5723
                                    {
5724
                                        range = new double[] {
5725
                                            Math.Min(range[0], temp[0]),
5726
                                            Math.Min(range[1], temp[1]),
5727
                                            Math.Max(range[2], temp[2]),
5728
                                            Math.Max(range[3], temp[3])
5729
                                        };
5730
                                    }
5731
                                }
5732
                            }
5733
                            if (range != null)
5734
                                correctList.Add(note);
5735
                            note.SPPID.Range = range;
5736

    
5737

    
5738
                            _LMItemNote.Commit();
5739
                        }
5740
                    }
5741
                }
5742
            }
5743

    
5744
            if (_LMAAttribute != null)
5745
                ReleaseCOMObjects(_LMAAttribute);
5746
            if (_LMItemNote != null)
5747
                ReleaseCOMObjects(_LMItemNote);
5748
            if (_LMSymbol != null)
5749
                ReleaseCOMObjects(_LMSymbol);
5750
        }
5751

    
5752
        private void NoteCorrectModeling(Note note, List<Note> endList)
5753
        {
5754
            bool needRemodeling = false;
5755
            bool loop = true;
5756
            GridSetting gridSetting = GridSetting.GetInstance();
5757
            while (loop)
5758
            {
5759
                loop = false;
5760
                foreach (var overlap in endList)
5761
                {
5762
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5763
                    {
5764
                        double tempX = 0;
5765
                        double tempY = 0;
5766
                        bool overlapX = false;
5767
                        bool overlapY = false;
5768
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5769
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5770
                        if (overlapY && angle >= 45)
5771
                        {
5772
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5773
                            double move = gridSetting.Length * count;
5774
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5775
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5776
                            needRemodeling = true;
5777
                            loop = true;
5778
                        }
5779
                        if (overlapX && angle <= 45)
5780
                        {
5781
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5782
                            double move = gridSetting.Length * count;
5783
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5784
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5785
                            needRemodeling = true;
5786
                            loop = true;
5787
                        }
5788
                    }
5789
                }
5790
            }
5791

    
5792

    
5793
            if (needRemodeling)
5794
            {
5795
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5796
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5797
                note.SPPID.RepresentationId = null;
5798

    
5799
                LMItemNote _LMItemNote = null;
5800
                LMAAttribute _LMAAttribute = null;
5801
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5802
                if (_LMSymbol != null)
5803
                {
5804
                    _LMSymbol.Commit();
5805
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5806
                    if (_LMItemNote != null)
5807
                    {
5808
                        _LMItemNote.Commit();
5809
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5810
                        if (_LMAAttribute != null)
5811
                        {
5812
                            _LMAAttribute.set_Value(note.VALUE);
5813
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5814
                            _LMItemNote.Commit();
5815

    
5816
                            ReleaseCOMObjects(_LMAAttribute);
5817
                            ReleaseCOMObjects(_LMItemNote);
5818
                        }
5819
                    }
5820
                }
5821

    
5822
                ReleaseCOMObjects(symbol);
5823
                symbol = null;
5824
                ReleaseCOMObjects(_LMItemNote);
5825
                _LMItemNote = null;
5826
                ReleaseCOMObjects(_LMAAttribute);
5827
                _LMAAttribute = null;
5828
                ReleaseCOMObjects(_LMSymbol);
5829
                _LMSymbol = null;
5830
            }
5831

    
5832
            endList.Add(note);
5833
        }
5834

    
5835
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5836
        {
5837
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5838
            if (modelItem != null)
5839
            {
5840
                foreach (LMRepresentation rep in modelItem.Representations)
5841
                {
5842
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5843
                    {
5844
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5845
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5846
                        {
5847
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5848
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5849
                            if (modelItemIds.Count == 1)
5850
                            {
5851
                                string joinModelItemId = modelItemIds[0];
5852
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5853
                                if (survivorId != null)
5854
                                    break;
5855
                            }
5856
                        }
5857
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5858
                        {
5859
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5860
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5861
                            if (modelItemIds.Count == 1)
5862
                            {
5863
                                string joinModelItemId = modelItemIds[0];
5864
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5865
                                if (survivorId != null)
5866
                                    break;
5867
                            }
5868
                        }
5869
                    }
5870
                }
5871
            }
5872
        }
5873

    
5874
        /// <summary>
5875
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5876
        /// </summary>
5877
        /// <param name="x"></param>
5878
        /// <param name="y"></param>
5879
        /// <param name="originX"></param>
5880
        /// <param name="originY"></param>
5881
        /// <param name="SPPIDLabelLocation"></param>
5882
        /// <param name="location"></param>
5883
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5884
        {
5885
            if (location == Location.None)
5886
            {
5887
                x = originX;
5888
                y = originY;
5889
            }
5890
            else
5891
            {
5892
                if (location.HasFlag(Location.Center))
5893
                {
5894
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5895
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5896
                }
5897

    
5898
                if (location.HasFlag(Location.Left))
5899
                    x = SPPIDLabelLocation.X1;
5900
                else if (location.HasFlag(Location.Right))
5901
                    x = SPPIDLabelLocation.X2;
5902

    
5903
                if (location.HasFlag(Location.Down))
5904
                    y = SPPIDLabelLocation.Y1;
5905
                else if (location.HasFlag(Location.Up))
5906
                    y = SPPIDLabelLocation.Y2;
5907
            }
5908
        }
5909

    
5910
        /// <summary>
5911
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5912
        /// 1. Angle Valve
5913
        /// 2. 3개로 이루어진 Symbol Group
5914
        /// </summary>
5915
        /// <returns></returns>
5916
        private List<Symbol> GetPrioritySymbol()
5917
        {
5918
            DataTable symbolTable = document.SymbolTable;
5919
            // List에 순서대로 쌓는다.
5920
            List<Symbol> symbols = new List<Symbol>();
5921

    
5922
            // Angle Valve 부터
5923
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5924
            {
5925
                if (!symbols.Contains(symbol))
5926
                {
5927
                    double originX = 0;
5928
                    double originY = 0;
5929

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

    
5934
                    SlopeType slopeType1 = SlopeType.None;
5935
                    SlopeType slopeType2 = SlopeType.None;
5936
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5937
                    {
5938
                        double connectorX = 0;
5939
                        double connectorY = 0;
5940
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5941
                        if (slopeType1 == SlopeType.None)
5942
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5943
                        else
5944
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5945
                    }
5946

    
5947
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5948
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5949
                        symbols.Add(symbol);
5950
                }
5951
            }
5952

    
5953
            List<Symbol> tempSymbols = new List<Symbol>();
5954
            // Conn 갯수 기준
5955
            foreach (var item in document.SYMBOLS)
5956
            {
5957
                if (!symbols.Contains(item))
5958
                    tempSymbols.Add(item);
5959
            }
5960
            tempSymbols.Sort(SortSymbolPriority);
5961
            symbols.AddRange(tempSymbols);
5962

    
5963
            return symbols;
5964
        }
5965

    
5966
        private void SetPriorityLine(List<Line> lines)
5967
        {
5968
            lines.Sort(SortLinePriority);
5969

    
5970
            int SortLinePriority(Line a, Line b)
5971
            {
5972
                // Branch 없는것부터
5973
                int branchRetval = CompareBranchLine(a, b);
5974
                if (branchRetval != 0)
5975
                {
5976
                    return branchRetval;
5977
                }
5978
                else
5979
                {
5980
                    // Symbol 연결 갯수
5981
                    int connSymbolRetval = CompareConnSymbol(a, b);
5982
                    if (connSymbolRetval != 0)
5983
                    {
5984
                        return connSymbolRetval;
5985
                    }
5986
                    else
5987
                    {
5988
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5989
                        int connItemRetval = CompareConnItem(a, b);
5990
                        if (connItemRetval != 0)
5991
                        {
5992
                            return connItemRetval;
5993
                        }
5994
                        else
5995
                        {
5996
                            // ConnectedItem이 없는것
5997
                            int noneConnRetval = CompareNoneConn(a, b);
5998
                            if (noneConnRetval != 0)
5999
                            {
6000
                                return noneConnRetval;
6001
                            }
6002
                            else
6003
                            {
6004

    
6005
                            }
6006
                        }
6007
                    }
6008
                }
6009

    
6010
                return 0;
6011
            }
6012

    
6013
            int CompareNotSegmentLine(Line a, Line b)
6014
            {
6015
                List<Connector> connectorsA = a.CONNECTORS
6016
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6017
                    .ToList();
6018

    
6019
                List<Connector> connectorsB = b.CONNECTORS
6020
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6021
                    .ToList();
6022

    
6023
                // 오름차순
6024
                return connectorsB.Count.CompareTo(connectorsA.Count);
6025
            }
6026

    
6027
            int CompareConnSymbol(Line a, Line b)
6028
            {
6029
                List<Connector> connectorsA = a.CONNECTORS
6030
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6031
                    .ToList();
6032

    
6033
                List<Connector> connectorsB = b.CONNECTORS
6034
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6035
                    .ToList();
6036

    
6037
                // 오름차순
6038
                return connectorsB.Count.CompareTo(connectorsA.Count);
6039
            }
6040

    
6041
            int CompareConnItem(Line a, Line b)
6042
            {
6043
                List<Connector> connectorsA = a.CONNECTORS
6044
                    .Where(conn => conn.ConnectedObject != null && 
6045
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
6046
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6047
                    .ToList();
6048

    
6049
                List<Connector> connectorsB = b.CONNECTORS
6050
                    .Where(conn => conn.ConnectedObject != null &&
6051
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6052
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6053
                    .ToList();
6054

    
6055
                // 오름차순
6056
                return connectorsB.Count.CompareTo(connectorsA.Count);
6057
            }
6058

    
6059
            int CompareBranchLine(Line a, Line b)
6060
            {
6061
                List<Connector> connectorsA = a.CONNECTORS
6062
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6063
                    .ToList();
6064
                List<Connector> connectorsB = b.CONNECTORS
6065
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6066
                    .ToList();
6067

    
6068
                // 내림차순
6069
                return connectorsA.Count.CompareTo(connectorsB.Count);
6070
            }
6071

    
6072
            int CompareNoneConn(Line a, Line b)
6073
            {
6074
                List<Connector> connectorsA = a.CONNECTORS
6075
                    .Where(conn => conn.ConnectedObject == null)
6076
                    .ToList();
6077

    
6078
                List<Connector> connectorsB = b.CONNECTORS
6079
                    .Where(conn => conn.ConnectedObject == null)
6080
                    .ToList();
6081

    
6082
                // 오름차순
6083
                return connectorsB.Count.CompareTo(connectorsA.Count);
6084
            }
6085
        }
6086

    
6087
        private void SortText(List<Text> texts)
6088
        {
6089
            texts.Sort(Sort);
6090

    
6091
            int Sort(Text a, Text b)
6092
            {
6093
                int yRetval = CompareY(a, b);
6094
                if (yRetval != 0)
6095
                {
6096
                    return yRetval;
6097
                }
6098
                else
6099
                {
6100
                    return CompareX(a, b);
6101
                }
6102
            }
6103

    
6104
            int CompareY(Text a, Text b)
6105
            {
6106
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6107
            }
6108

    
6109
            int CompareX(Text a, Text b)
6110
            {
6111
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6112
            }
6113
        }
6114
        private void SortNote(List<Note> notes)
6115
        {
6116
            notes.Sort(Sort);
6117

    
6118
            int Sort(Note a, Note b)
6119
            {
6120
                int yRetval = CompareY(a, b);
6121
                if (yRetval != 0)
6122
                {
6123
                    return yRetval;
6124
                }
6125
                else
6126
                {
6127
                    return CompareX(a, b);
6128
                }
6129
            }
6130

    
6131
            int CompareY(Note a, Note b)
6132
            {
6133
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6134
            }
6135

    
6136
            int CompareX(Note a, Note b)
6137
            {
6138
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6139
            }
6140
        }
6141

    
6142
        private void SortBranchLines()
6143
        {
6144
            BranchLines.Sort(SortBranchLine);
6145
            int SortBranchLine(Line a, Line b)
6146
            {
6147
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6148
                 x.ConnectedObject.GetType() == typeof(Line) &&
6149
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6150
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6151

    
6152
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6153
                 x.ConnectedObject.GetType() == typeof(Line) &&
6154
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6155
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6156

    
6157
                // 내림차순
6158
                return countA.CompareTo(countB);
6159
            }
6160
        }
6161

    
6162
        private static int SortSymbolPriority(Symbol a, Symbol b)
6163
        {
6164
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6165
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6166
            int retval = countB.CompareTo(countA);
6167
            if (retval != 0)
6168
                return retval;
6169
            else
6170
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6171
        }
6172

    
6173
        private string GetSPPIDFileName(LMModelItem modelItem)
6174
        {
6175
            string symbolPath = null;
6176
            foreach (LMRepresentation rep in modelItem.Representations)
6177
            {
6178
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6179
                {
6180
                    symbolPath = rep.get_FileName();
6181
                    break;
6182
                }
6183
            }
6184
            return symbolPath;
6185
        }
6186

    
6187
        private string GetSPPIDFileName(string modelItemId)
6188
        {
6189
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6190
            string symbolPath = null;
6191
            foreach (LMRepresentation rep in modelItem.Representations)
6192
            {
6193
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6194
                {
6195
                    symbolPath = rep.get_FileName();
6196
                    break;
6197
                }
6198
            }
6199
            ReleaseCOMObjects(modelItem);
6200
            return symbolPath;
6201
        }
6202

    
6203
        /// <summary>
6204
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6205
        /// </summary>
6206
        /// <param name="graphicOID"></param>
6207
        /// <param name="milliseconds"></param>
6208
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6209
        {
6210
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6211
            {
6212
                double minX = 0;
6213
                double minY = 0;
6214
                double maxX = 0;
6215
                double maxY = 0;
6216
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6217
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6218

    
6219
                Thread.Sleep(milliseconds);
6220
            }
6221
        }
6222

    
6223
        /// <summary>
6224
        /// ComObject를 Release
6225
        /// </summary>
6226
        /// <param name="objVars"></param>
6227
        public void ReleaseCOMObjects(params object[] objVars)
6228
        {
6229
            if (objVars != null)
6230
            {
6231
                int intNewRefCount = 0;
6232
                foreach (object obj in objVars)
6233
                {
6234
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6235
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6236
                }
6237
            }
6238
        }
6239

    
6240
        /// IDisposable 구현
6241
        ~AutoModeling()
6242
        {
6243
            this.Dispose(false);
6244
        }
6245

    
6246
        private bool disposed;
6247
        public void Dispose()
6248
        {
6249
            this.Dispose(true);
6250
            GC.SuppressFinalize(this);
6251
        }
6252

    
6253
        protected virtual void Dispose(bool disposing)
6254
        {
6255
            if (this.disposed) return;
6256
            if (disposing)
6257
            {
6258
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6259
            }
6260
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6261
            this.disposed = true;
6262
        }
6263
    }
6264
}
클립보드 이미지 추가 (최대 크기: 500 MB)