프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ dc5c5b3c

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

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

    
39
        public string DocumentLabelText { get; set; }
40

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

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

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

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

    
71
                }
72
            }
73
        }
74

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

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

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

    
161
                Log.Write("End Modeling");
162
                radApp.ActiveWindow.Fit();
163

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

    
181
                ReleaseCOMObjects(dataSource);
182
                dataSource = null;
183
                ReleaseCOMObjects(_placement);
184
                _placement = null;
185

    
186
                Thread.Sleep(1000);
187
            }
188
        }
189

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

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

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

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

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

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

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

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

    
400
                                    // 제거
401
                                    RemoveSymbol(connSymbol);
402
                                    RemoveLine(item);
403

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

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

    
424
                void SetCoordinate()
425
                {
426
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
427
                    if (branchConnector != null)
428
                    {
429
                        Line connLine = branchConnector.ConnectedObject as Line;
430
                        double x = 0;
431
                        double y = 0;
432
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
433
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
434
                        if (targetConnector != null)
435
                        {
436
                            List<Symbol> group = new List<Symbol>();
437
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
438
                            if (item.SlopeType == SlopeType.HORIZONTAL)
439
                            {
440
                                item.SPPID.START_Y = y;
441
                                item.SPPID.END_Y = y;
442
                                foreach (var symbol in group)
443
                                {
444
                                    symbol.SPPID.ORIGINAL_Y = y;
445
                                    symbol.SPPID.SPPID_Y = y;
446
                                }
447
                            }
448
                            else if (item.SlopeType == SlopeType.VERTICAL)
449
                            {
450
                                item.SPPID.START_X = x;
451
                                item.SPPID.END_X = x;
452
                                foreach (var symbol in group)
453
                                {
454
                                    symbol.SPPID.ORIGINAL_X = x;
455
                                    symbol.SPPID.SPPID_X = x;
456
                                }
457
                            }
458
                        }
459
                        ReleaseCOMObjects(targetConnector);
460
                        targetConnector = null;
461
                    }
462
                }
463
            }
464
        }
465
        private void RunClearNominalDiameter()
466
        {
467
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
468
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
469
            List<string> endClearModelItemID = new List<string>();
470
            for (int i = 0; i < document.LINES.Count; i++)
471
            {
472
                Line item = document.LINES[i];
473
                string modelItemID = item.SPPID.ModelItemId;
474
                if (!string.IsNullOrEmpty(modelItemID))
475
                {
476
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
477
                    if (modelItem != null)
478
                    {
479
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
480
                        if (attribute != null)
481
                            attribute.set_Value(DBNull.Value);
482

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

    
537
                                    modelItem.Commit();
538
                                    ReleaseCOMObjects(modelItem);
539
                                    modelItem = null;
540
                                }
541
                            }
542
                        }
543
                        foreach (LMConnector connector in symbol.Connect2Connectors)
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
                    }
562
                    ReleaseCOMObjects(symbol);
563
                    symbol = null;
564
                }
565
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
566
            }
567
        }
568
        private void RunClearValueInconsistancy()
569
        {
570
            int count = 1;
571
            bool loop = true;
572
            while (loop)
573
            {
574
                loop = false;
575
                LMAFilter filter = new LMAFilter();
576
                LMACriterion criterion = new LMACriterion();
577
                filter.ItemType = "Relationship";
578
                criterion.SourceAttributeName = "SP_DRAWINGID";
579
                criterion.Operator = "=";
580
                criterion.set_ValueAttribute(drawingID);
581
                filter.get_Criteria().Add(criterion);
582

    
583
                LMRelationships relationships = new LMRelationships();
584
                relationships.Collect(dataSource, Filter: filter);
585

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

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

    
745
                    }
746
                }
747
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
748
            }
749

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

    
810
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
811
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
812
            SortNote(correctList);
813
            List<Note> endList = new List<Note>();
814
            if (correctList.Count > 0)
815
                endList.Add(correctList[0]);
816
            foreach (var item in correctList)
817
                try
818
                {
819
                    if (!endList.Contains(item))
820
                        NoteCorrectModeling(item, endList);
821
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
822
                }
823
                catch (Exception ex)
824
                {
825
                    Log.Write("Error in NoteModeling");
826
                    Log.Write("UID : " + item.UID);
827
                    Log.Write(ex.Message);
828
                    Log.Write(ex.StackTrace);
829
                }
830
        }
831
        private void RunTextModeling()
832
        {
833
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
834
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
835
            SortText(document.TEXTINFOS);
836
            foreach (var item in document.TEXTINFOS)
837
                try
838
                {
839
                    if (item.ASSOCIATION)
840
                        AssociationTextModeling(item);
841
                    else
842
                        NormalTextModeling(item);
843
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
844
                }
845
                catch (Exception ex)
846
                {
847
                    Log.Write("Error in TextModeling");
848
                    Log.Write("UID : " + item.UID);
849
                    Log.Write(ex.Message);
850
                    Log.Write(ex.StackTrace);
851
                }
852
        }
853
        private void RunInputLineNumberAttribute()
854
        {
855
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
856
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
857
            List<string> endLine = new List<string>();
858
            foreach (var item in document.LINENUMBERS)
859
                try
860
                {
861
                    InputLineNumberAttribute(item, endLine);
862
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
863
                }
864
                catch (Exception ex)
865
                {
866
                    Log.Write("Error in InputLineNumberAttribute");
867
                    Log.Write("UID : " + item.UID);
868
                    Log.Write(ex.Message);
869
                    Log.Write(ex.StackTrace);
870
                }
871
        }
872
        private void RunInputSymbolAttribute()
873
        {
874
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
875
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
876
            foreach (var item in document.SYMBOLS)
877
                try
878
                {
879
                    InputSymbolAttribute(item, item.ATTRIBUTES);
880
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
881
                }
882
                catch (Exception ex)
883
                {
884
                    Log.Write("Error in InputSymbolAttribute");
885
                    Log.Write("UID : " + item.UID);
886
                    Log.Write(ex.Message);
887
                    Log.Write(ex.StackTrace);
888
                }
889
        }
890
        private void RunInputSpecBreakAttribute()
891
        {
892
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
893
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
894
            foreach (var item in document.SpecBreaks)
895
                try
896
                {
897
                    InputSpecBreakAttribute(item);
898
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
899
                }
900
                catch (Exception ex)
901
                {
902
                    Log.Write("Error in InputSpecBreakAttribute");
903
                    Log.Write("UID : " + item.UID);
904
                    Log.Write(ex.Message);
905
                    Log.Write(ex.StackTrace);
906
                }
907
        }
908
        private void RunInputEndBreakAttribute()
909
        {
910
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
911
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
912
            foreach (var item in document.EndBreaks)
913
                try
914
                {
915
                    InputEndBreakAttribute(item);
916
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
917
                }
918
                catch (Exception ex)
919
                {
920
                    Log.Write("Error in RunInputEndBreakAttribute");
921
                    Log.Write("UID : " + item.UID);
922
                    Log.Write(ex.Message);
923
                    Log.Write(ex.StackTrace);
924
                }
925
        }
926
        private void RunLabelSymbolModeling()
927
        {
928
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
929
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
930
            foreach (var item in document.SYMBOLS)
931
                try
932
                {
933
                    LabelSymbolModeling(item);
934
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
935
                }
936
                catch (Exception ex)
937
                {
938
                    Log.Write("Error in LabelSymbolModeling");
939
                    Log.Write("UID : " + item.UID);
940
                    Log.Write(ex.Message);
941
                    Log.Write(ex.StackTrace);
942
                }
943
        }
944
        private void RunCorrectAssociationText()
945
        {
946
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
947
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
948
            List<Text> endTexts = new List<Text>();
949
            foreach (var item in document.TEXTINFOS)
950
            {
951
                try
952
                {
953
                    if (item.ASSOCIATION && !endTexts.Contains(item))
954
                        AssociationTextCorrectModeling(item, endTexts);
955
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
956
                }
957
                catch (Exception ex)
958
                {
959
                    Log.Write("Error in RunCorrectAssociationText");
960
                    Log.Write("UID : " + item.UID);
961
                    Log.Write(ex.Message);
962
                    Log.Write(ex.StackTrace);
963
                }
964
                
965
            }
966

    
967
            foreach (var item in document.LINENUMBERS)
968
            {
969
                try
970
                {
971
                    LineNumberCorrectModeling(item);
972
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
973
                }
974
                catch (Exception ex)
975
                {
976
                    Log.Write("Error in RunCorrectAssociationText");
977
                    Log.Write("UID : " + item.UID);
978
                    Log.Write(ex.Message);
979
                    Log.Write(ex.StackTrace);
980
                }
981
            }
982
        }
983
        private void RunETC()
984
        {
985
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, FlowMarkRepIds.Count);
986
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "ETC");
987
            foreach (var item in FlowMarkRepIds)
988
            {
989
                LMLabelPersist label = dataSource.GetLabelPersist(item);
990
                if (label != null)
991
                {
992
                    label.get_GraphicOID();
993
                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[label.get_GraphicOID().ToString()] as DependencyObject;
994
                    if (dependency != null)
995
                        dependency.BringToFront();
996
                }
997
                ReleaseCOMObjects(label);
998
                label = null;
999
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1000
            }
1001
        }
1002
        /// <summary>
1003
        /// 도면 생성 메서드
1004
        /// </summary>
1005
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1006
        {
1007
            Log.Write("------------------ Start create document ------------------");
1008
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1009
            Log.Write("Drawing name : " + drawingName);
1010
            Log.Write("Drawing number : " + drawingNumber);
1011
            Thread.Sleep(1000);
1012
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1013
            if (newDrawing != null)
1014
            {
1015
                document.SPPID_DrawingNumber = drawingNumber;
1016
                document.SPPID_DrawingName = drawingName;
1017
                Thread.Sleep(1000);
1018
                radApp.ActiveWindow.Fit();
1019
                Thread.Sleep(1000);
1020
                radApp.ActiveWindow.Zoom = 2000;
1021
                Thread.Sleep(2000);
1022

    
1023
                //current LMDrawing 가져오기
1024
                LMAFilter filter = new LMAFilter();
1025
                LMACriterion criterion = new LMACriterion();
1026
                filter.ItemType = "Drawing";
1027
                criterion.SourceAttributeName = "Name";
1028
                criterion.Operator = "=";
1029
                criterion.set_ValueAttribute(drawingName);
1030
                filter.get_Criteria().Add(criterion);
1031

    
1032
                LMDrawings drawings = new LMDrawings();
1033
                drawings.Collect(dataSource, Filter: filter);
1034

    
1035
                drawingID = ((dynamic)drawings).Nth(1).Id;
1036
                ReleaseCOMObjects(filter);
1037
                ReleaseCOMObjects(criterion);
1038
                ReleaseCOMObjects(drawings);
1039
                filter = null;
1040
                criterion = null;
1041
                drawings = null;
1042
            }
1043
            else
1044
                Log.Write("Fail Create Drawing");
1045

    
1046
            if (newDrawing != null)
1047
            {
1048
                SetBorderFile();
1049
                return true;
1050
            }
1051
            else
1052
                return false;
1053
        }
1054

    
1055
        private void SetBorderFile()
1056
        {
1057
            ETCSetting setting = ETCSetting.GetInstance();
1058

    
1059
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1060
            {
1061
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1062
                {
1063
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1064
                    {
1065
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1066
                        smartFrame.Update();
1067
                    }
1068
                        
1069
                }
1070
            }
1071
        }
1072

    
1073
        /// <summary>
1074
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1075
        /// </summary>
1076
        /// <param name="drawingName"></param>
1077
        /// <param name="drawingNumber"></param>
1078
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1079
        {
1080
            LMDrawings drawings = new LMDrawings();
1081
            drawings.Collect(dataSource);
1082

    
1083
            List<string> drawingNameList = new List<string>();
1084
            List<string> drawingNumberList = new List<string>();
1085

    
1086
            foreach (LMDrawing item in drawings)
1087
            {
1088
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1089
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1090
            }
1091

    
1092
            int nameLength = drawingName.Length;
1093
            while (drawingNameList.Contains(drawingName))
1094
            {
1095
                if (nameLength == drawingName.Length)
1096
                    drawingName += "-1";
1097
                else
1098
                {
1099
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1100
                    drawingName = drawingName.Substring(0, nameLength + 1);
1101
                    drawingName += ++index;
1102
                }
1103
            }
1104

    
1105
            int numberLength = drawingNumber.Length;
1106
            while (drawingNameList.Contains(drawingNumber))
1107
            {
1108
                if (numberLength == drawingNumber.Length)
1109
                    drawingNumber += "-1";
1110
                else
1111
                {
1112
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1113
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1114
                    drawingNumber += ++index;
1115
                }
1116
            }
1117
            ReleaseCOMObjects(drawings);
1118
            drawings = null;
1119
        }
1120

    
1121
        /// <summary>
1122
        /// 도면 크기 구하는 메서드
1123
        /// </summary>
1124
        /// <returns></returns>
1125
        private bool DocumentCoordinateCorrection()
1126
        {
1127
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1128
            {
1129
                Log.Write("Setting Drawing X, Drawing Y");
1130
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1131
                Log.Write("Start coordinate correction");
1132
                document.CoordinateCorrection();
1133
                return true;
1134
            }
1135
            else
1136
            {
1137
                Log.Write("Need Drawing X, Y");
1138
                return false;
1139
            }
1140
        }
1141

    
1142
        /// <summary>
1143
        /// 심볼을 실제로 Modeling 메서드
1144
        /// </summary>
1145
        /// <param name="symbol">생성할 심볼</param>
1146
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1147
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1148
        {
1149
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1150
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1151
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1152
                return;
1153
            // 이미 모델링 됐을 경우
1154
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1155
                return;
1156

    
1157
            LMSymbol _LMSymbol = null;
1158

    
1159
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1160
            double x = symbol.SPPID.ORIGINAL_X;
1161
            double y = symbol.SPPID.ORIGINAL_Y;
1162
            int mirror = 0;
1163
            double angle = symbol.ANGLE;
1164

    
1165
            // OPC 일경우 180도 일때 Mirror
1166
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1167
                mirror = 1;
1168

    
1169
            // Mirror 계산
1170
            if (symbol.FLIP == 1)
1171
            {
1172
                mirror = 1;
1173
                angle += Math.PI;
1174
            }
1175

    
1176
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1177
            {
1178
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1179
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1180
                if (connector != null)
1181
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1182

    
1183
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1184
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1185
                if (temp != null)
1186
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1187
                ReleaseCOMObjects(temp);
1188
                temp = null;
1189

    
1190
                if (_LMSymbol != null && _TargetItem != null)
1191
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1192

    
1193
                ReleaseCOMObjects(_TargetItem);
1194
            }
1195
            else
1196
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1197

    
1198
            if (_LMSymbol != null)
1199
            {
1200
                _LMSymbol.Commit();
1201

    
1202
                // ConnCheck
1203
                List<string> ids = new List<string>();
1204
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1205
                {
1206
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1207
                        ids.Add(item.Id);
1208
                    ReleaseCOMObjects(item);
1209
                }
1210
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1211
                {
1212
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1213
                        ids.Add(item.Id);
1214
                    ReleaseCOMObjects(item);
1215
                }
1216

    
1217
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1218
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1219
                {
1220
                    double currentX = _LMSymbol.get_XCoordinate();
1221
                    double currentY = _LMSymbol.get_YCoordinate();
1222

    
1223

    
1224
                }
1225

    
1226
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1227
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1228
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1229

    
1230
                foreach (var item in symbol.ChildSymbols)
1231
                    CreateChildSymbol(item, _LMSymbol, symbol);
1232

    
1233
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1234
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1235

    
1236
                double[] range = null;
1237
                GetSPPIDSymbolRange(symbol, ref range);
1238
                symbol.SPPID.SPPID_Min_X = range[0];
1239
                symbol.SPPID.SPPID_Min_Y = range[1];
1240
                symbol.SPPID.SPPID_Max_X = range[2];
1241
                symbol.SPPID.SPPID_Max_Y = range[3];
1242

    
1243
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1244
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1245
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1246
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1247

    
1248
                ReleaseCOMObjects(_LMSymbol);
1249
            }
1250
        }
1251
        /// <summary>
1252
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1253
        /// Signal Point는 고려하지 않음
1254
        /// </summary>
1255
        /// <param name="symbol"></param>
1256
        /// <param name="_TargetItem"></param>
1257
        /// <param name="targetX"></param>
1258
        /// <param name="targetY"></param>
1259
        /// <returns></returns>
1260
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1261
        {
1262
            LMConnector tempConnector = null;
1263

    
1264
            List<Symbol> group = new List<Symbol>();
1265
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1266
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1267
            {
1268
                List<Connector> connectors = new List<Connector>();
1269
                foreach (var item in group)
1270
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1271
                /// Primary or Secondary Type Line만 고려
1272
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1273
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1274
                if (_connector != null)
1275
                {
1276
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1277
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1278
                    /// PipingPoint가 2개 이상만
1279
                    if (pointInfos.Count >= 2)
1280
                    {
1281
                        double lineX = 0;
1282
                        double lineY = 0;
1283
                        double length = 0;
1284
                        foreach (var item in pointInfos)
1285
                        {
1286
                            double tempX = item[1];
1287
                            double tempY = item[2];
1288

    
1289
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1290
                            if (calcDistance > length)
1291
                            {
1292
                                lineX = tempX;
1293
                                lineY = tempY;
1294
                            }
1295
                        }
1296

    
1297
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1298
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1299
                        placeRunInputs.AddPoint(-1, -1);
1300
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1301
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1302
                        if (tempConnector != null)
1303
                            tempConnector.Commit();
1304
                        ReleaseCOMObjects(_LMAItem);
1305
                        _LMAItem = null;
1306
                        ReleaseCOMObjects(placeRunInputs);
1307
                        placeRunInputs = null;
1308
                    }
1309
                }
1310
            }
1311

    
1312
            return tempConnector;
1313
        }
1314
        /// <summary>
1315
        /// Symbol의 PipingPoints를 구함
1316
        /// SignalPoint는 고려하지 않음
1317
        /// </summary>
1318
        /// <param name="symbol"></param>
1319
        /// <returns></returns>
1320
        private List<double[]> getPipingPoints(LMSymbol symbol)
1321
        {
1322
            LMModelItem modelItem = symbol.ModelItemObject;
1323
            LMPipingPoints pipingPoints = null;
1324
            if (modelItem.get_ItemTypeName() == "PipingComp")
1325
            {
1326
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1327
                pipingPoints = pipingComp.PipingPoints;
1328
                ReleaseCOMObjects(pipingComp);
1329
                pipingComp = null;
1330
            }
1331
            else if (modelItem.get_ItemTypeName() == "Instrument")
1332
            {
1333
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1334
                pipingPoints = instrument.PipingPoints;
1335
                ReleaseCOMObjects(instrument);
1336
                instrument = null;
1337
            }
1338
            else
1339
                Log.Write("다른 Type");
1340

    
1341
            List<double[]> info = new List<double[]>();
1342
            if (pipingPoints != null)
1343
            {
1344
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1345
                {
1346
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1347
                    {
1348
                        if (attribute.Name == "PipingPointNumber")
1349
                        {
1350
                            int index = Convert.ToInt32(attribute.get_Value());
1351
                            if (info.Find(loopX => loopX[0] == index) == null)
1352
                            {
1353
                                double x = 0;
1354
                                double y = 0;
1355
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1356
                                    info.Add(new double[] { index, x, y });
1357
                            }
1358
                        }
1359
                    }
1360
                }
1361
            }
1362
            ReleaseCOMObjects(modelItem);
1363
            modelItem = null;
1364
            ReleaseCOMObjects(pipingPoints);
1365
            pipingPoints = null;
1366

    
1367
            return info;
1368
        }
1369

    
1370
        private void RemoveSymbol(Symbol symbol)
1371
        {
1372
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1373
            {
1374
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1375
                if (_LMSymbol != null)
1376
                {
1377
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1378
                    ReleaseCOMObjects(_LMSymbol);
1379
                }
1380
            }
1381

    
1382
            symbol.SPPID.RepresentationId = string.Empty;
1383
            symbol.SPPID.ModelItemID = string.Empty;
1384
            symbol.SPPID.SPPID_X = double.NaN;
1385
            symbol.SPPID.SPPID_Y = double.NaN;
1386
            symbol.SPPID.SPPID_Min_X = double.NaN;
1387
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1388
            symbol.SPPID.SPPID_Max_X = double.NaN;
1389
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1390
        }
1391

    
1392
        private void RemoveSymbol(List<Symbol> symbols)
1393
        {
1394
            foreach (var symbol in symbols)
1395
            {
1396
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1397
                {
1398
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1399
                    if (_LMSymbol != null)
1400
                    {
1401
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1402
                        ReleaseCOMObjects(_LMSymbol);
1403
                    }
1404
                }
1405

    
1406
                symbol.SPPID.RepresentationId = string.Empty;
1407
                symbol.SPPID.ModelItemID = string.Empty;
1408
                symbol.SPPID.SPPID_X = double.NaN;
1409
                symbol.SPPID.SPPID_Y = double.NaN;
1410
                symbol.SPPID.SPPID_Min_X = double.NaN;
1411
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1412
                symbol.SPPID.SPPID_Max_X = double.NaN;
1413
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1414
            }
1415
        }
1416

    
1417
        /// <summary>
1418
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1419
        /// </summary>
1420
        /// <param name="targetConnector"></param>
1421
        /// <param name="targetSymbol"></param>
1422
        /// <param name="x"></param>
1423
        /// <param name="y"></param>
1424
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1425
        {
1426
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1427

    
1428
            double[] range = null;
1429
            List<double[]> points = new List<double[]>();
1430
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1431
            double x1 = range[0];
1432
            double y1 = range[1];
1433
            double x2 = range[2];
1434
            double y2 = range[3];
1435

    
1436
            // Origin 기준 Connector의 위치차이
1437
            double sceneX = 0;
1438
            double sceneY = 0;
1439
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1440
            double originX = 0;
1441
            double originY = 0;
1442
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1443
            double gapX = originX - sceneX;
1444
            double gapY = originY - sceneY;
1445

    
1446
            // SPPID Symbol과 ID2 심볼의 크기 차이
1447
            double sizeWidth = 0;
1448
            double sizeHeight = 0;
1449
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1450
            if (sizeWidth == 0 || sizeHeight == 0)
1451
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1452

    
1453
            double percentX = (x2 - x1) / sizeWidth;
1454
            double percentY = (y2 - y1) / sizeHeight;
1455

    
1456
            double SPPIDgapX = gapX * percentX;
1457
            double SPPIDgapY = gapY * percentY;
1458

    
1459
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1460
            double distance = double.MaxValue;
1461
            double[] resultPoint;
1462
            foreach (var point in points)
1463
            {
1464
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1465
                if (distance > result)
1466
                {
1467
                    distance = result;
1468
                    resultPoint = point;
1469
                    x = point[0];
1470
                    y = point[1];
1471
                }
1472
            }
1473

    
1474
            ReleaseCOMObjects(_TargetItem);
1475
        }
1476

    
1477
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1478
        {
1479
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1480
            if (index == 0)
1481
            {
1482
                x = targetLine.SPPID.START_X;
1483
                y = targetLine.SPPID.START_Y;
1484
            }
1485
            else
1486
            {
1487
                x = targetLine.SPPID.END_X;
1488
                y = targetLine.SPPID.END_Y;
1489
            }
1490
        }
1491

    
1492
        /// <summary>
1493
        /// SPPID Symbol의 Range를 구한다.
1494
        /// </summary>
1495
        /// <param name="symbol"></param>
1496
        /// <param name="range"></param>
1497
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1498
        {
1499
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1500
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1501
            double x1 = 0;
1502
            double y1 = 0;
1503
            double x2 = 0;
1504
            double y2 = 0;
1505
            symbol2d.Range(out x1, out y1, out x2, out y2);
1506
            range = new double[] { x1, y1, x2, y2 };
1507

    
1508
            for (int i = 1; i < int.MaxValue; i++)
1509
            {
1510
                double connX = 0;
1511
                double connY = 0;
1512
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1513
                    points.Add(new double[] { connX, connY });
1514
                else
1515
                    break;
1516
            }
1517

    
1518
            foreach (var childSymbol in symbol.ChildSymbols)
1519
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1520

    
1521
            ReleaseCOMObjects(_TargetItem);
1522
        }
1523

    
1524
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1525
        {
1526
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1527
            if (_TargetItem != null)
1528
            {
1529
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1530
                double x1 = 0;
1531
                double y1 = 0;
1532
                double x2 = 0;
1533
                double y2 = 0;
1534
                if (!bForGraphic)
1535
                {
1536
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1537
                    range = new double[] { x1, y1, x2, y2 };
1538
                }
1539
                else
1540
                {
1541
                    x1 = double.MaxValue;
1542
                    y1 = double.MaxValue;
1543
                    x2 = double.MinValue;
1544
                    y2 = double.MinValue;
1545
                    range = new double[] { x1, y1, x2, y2 };
1546

    
1547
                    foreach (var item in symbol2d.DrawingObjects)
1548
                    {
1549
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1550
                        {
1551
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1552
                            if (rangeObject.Layer == "Default")
1553
                            {
1554
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1555
                                range = new double[] {
1556
                                Math.Min(x1, range[0]),
1557
                                Math.Min(y1, range[1]),
1558
                                Math.Max(x2, range[2]),
1559
                                Math.Max(y2, range[3])
1560
                            };
1561
                            }
1562
                        }
1563
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1564
                        {
1565
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1566
                            if (rangeObject.Layer == "Default")
1567
                            {
1568
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1569
                                range = new double[] {
1570
                                Math.Min(x1, range[0]),
1571
                                Math.Min(y1, range[1]),
1572
                                Math.Max(x2, range[2]),
1573
                                Math.Max(y2, range[3])
1574
                            };
1575
                            }
1576
                        }
1577
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1578
                        {
1579
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1580
                            if (rangeObject.Layer == "Default")
1581
                            {
1582
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1583
                                range = new double[] {
1584
                                Math.Min(x1, range[0]),
1585
                                Math.Min(y1, range[1]),
1586
                                Math.Max(x2, range[2]),
1587
                                Math.Max(y2, range[3])
1588
                            };
1589
                            }
1590
                        }
1591
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1592
                        {
1593
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1594
                            if (rangeObject.Layer == "Default")
1595
                            {
1596
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1597
                                range = new double[] {
1598
                                Math.Min(x1, range[0]),
1599
                                Math.Min(y1, range[1]),
1600
                                Math.Max(x2, range[2]),
1601
                                Math.Max(y2, range[3])
1602
                            };
1603
                            }
1604
                        }
1605
                    }
1606
                }
1607

    
1608
                if (!bOnlySymbol)
1609
                {
1610
                    foreach (var childSymbol in symbol.ChildSymbols)
1611
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1612
                }
1613
                ReleaseCOMObjects(_TargetItem);
1614
            }
1615
        }
1616

    
1617
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1618
        {
1619
            if (labelPersist != null)
1620
            {
1621
                double x1 = double.MaxValue;
1622
                double y1 = double.MaxValue;
1623
                double x2 = double.MinValue;
1624
                double y2 = double.MinValue;
1625
                range = new double[] { x1, y1, x2, y2 };
1626

    
1627
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1628
                foreach (var item in dependency.DrawingObjects)
1629
                {
1630
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1631
                    if (textBox != null)
1632
                    {
1633
                        if (dependency != null)
1634
                        {
1635
                            double tempX1;
1636
                            double tempY1;
1637
                            double tempX2;
1638
                            double tempY2;
1639
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1640
                            x1 = Math.Min(x1, tempX1);
1641
                            y1 = Math.Min(y1, tempY1);
1642
                            x2 = Math.Max(x2, tempX2);
1643
                            y2 = Math.Max(y2, tempY2);
1644

    
1645
                            range = new double[] { x1, y1, x2, y2 };
1646
                        }
1647
                    }
1648
                }
1649
                
1650
            }
1651
        }
1652

    
1653
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1654
        {
1655
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1656
            foreach (var symbol in symbols)
1657
            {
1658
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1659
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1660
                double x1 = 0;
1661
                double y1 = 0;
1662
                double x2 = 0;
1663
                double y2 = 0;
1664
                symbol2d.Range(out x1, out y1, out x2, out y2);
1665

    
1666
                tempRange[0] = Math.Min(tempRange[0], x1);
1667
                tempRange[1] = Math.Min(tempRange[1], y1);
1668
                tempRange[2] = Math.Max(tempRange[2], x2);
1669
                tempRange[3] = Math.Max(tempRange[3], y2);
1670

    
1671
                foreach (var childSymbol in symbol.ChildSymbols)
1672
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1673

    
1674
                ReleaseCOMObjects(_TargetItem);
1675
            }
1676

    
1677
            range = tempRange;
1678
        }
1679

    
1680
        /// <summary>
1681
        /// Child Modeling 된 Symbol의 Range를 구한다.
1682
        /// </summary>
1683
        /// <param name="childSymbol"></param>
1684
        /// <param name="range"></param>
1685
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1686
        {
1687
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1688
            if (_ChildSymbol != null)
1689
            {
1690
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1691
                double x1 = 0;
1692
                double y1 = 0;
1693
                double x2 = 0;
1694
                double y2 = 0;
1695
                symbol2d.Range(out x1, out y1, out x2, out y2);
1696
                range[0] = Math.Min(range[0], x1);
1697
                range[1] = Math.Min(range[1], y1);
1698
                range[2] = Math.Max(range[2], x2);
1699
                range[3] = Math.Max(range[3], y2);
1700

    
1701
                for (int i = 1; i < int.MaxValue; i++)
1702
                {
1703
                    double connX = 0;
1704
                    double connY = 0;
1705
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1706
                        points.Add(new double[] { connX, connY });
1707
                    else
1708
                        break;
1709
                }
1710

    
1711
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1712
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1713

    
1714
                ReleaseCOMObjects(_ChildSymbol);
1715
            }
1716
        }
1717

    
1718
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1719
        {
1720
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1721
            if (_ChildSymbol != null)
1722
            {
1723
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1724
                double x1 = 0;
1725
                double y1 = 0;
1726
                double x2 = 0;
1727
                double y2 = 0;
1728
                symbol2d.Range(out x1, out y1, out x2, out y2);
1729
                range[0] = Math.Min(range[0], x1);
1730
                range[1] = Math.Min(range[1], y1);
1731
                range[2] = Math.Max(range[2], x2);
1732
                range[3] = Math.Max(range[3], y2);
1733

    
1734
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1735
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1736
                ReleaseCOMObjects(_ChildSymbol);
1737
            }
1738
        }
1739

    
1740
        /// <summary>
1741
        /// Label Symbol Modeling
1742
        /// </summary>
1743
        /// <param name="symbol"></param>
1744
        private void LabelSymbolModeling(Symbol symbol)
1745
        {
1746
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1747
            {
1748
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1749
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1750
                    return;
1751
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1752

    
1753
                string symbolUID = itemAttribute.VALUE;
1754
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1755
                if (targetItem != null &&
1756
                    (targetItem.GetType() == typeof(Symbol) ||
1757
                    targetItem.GetType() == typeof(Equipment)))
1758
                {
1759
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1760
                    string sRep = null;
1761
                    if (targetItem.GetType() == typeof(Symbol))
1762
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1763
                    else if (targetItem.GetType() == typeof(Equipment))
1764
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1765
                    if (!string.IsNullOrEmpty(sRep))
1766
                    {
1767
                        // LEADER Line 검사
1768
                        bool leaderLine = false;
1769
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1770
                        if (symbolMapping != null)
1771
                            leaderLine = symbolMapping.LEADERLINE;
1772

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

    
1777
                        //Leader 선 센터로
1778
                        if (_LMLabelPresist != null)
1779
                        {
1780
                            // Target Item에 Label의 Attribute Input
1781
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1782

    
1783
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1784
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1785
                            if (dependency != null)
1786
                            {
1787
                                bool result = false;
1788
                                foreach (var attributes in dependency.AttributeSets)
1789
                                {
1790
                                    foreach (var attribute in attributes)
1791
                                    {
1792
                                        string name = attribute.Name;
1793
                                        string value = attribute.GetValue().ToString();
1794
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1795
                                        {
1796
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1797
                                            {
1798
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1799
                                                {
1800
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1801
                                                    double prevX = _TargetItem.get_XCoordinate();
1802
                                                    double prevY = _TargetItem.get_YCoordinate();
1803
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1804
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1805
                                                    result = true;
1806
                                                    break;
1807
                                                }
1808
                                            }
1809
                                        }
1810

    
1811
                                        if (result)
1812
                                            break;
1813
                                    }
1814

    
1815
                                    if (result)
1816
                                        break;
1817
                                }
1818
                            }
1819

    
1820
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1821
                            _LMLabelPresist.Commit();
1822
                            ReleaseCOMObjects(_LMLabelPresist);
1823
                        }
1824

    
1825
                        ReleaseCOMObjects(_TargetItem);
1826
                    }
1827
                }
1828
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1829
                {
1830
                    Line targetLine = targetItem as Line;
1831
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1832
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1833
                    if (connectedLMConnector != null)
1834
                    {
1835
                        // LEADER Line 검사
1836
                        bool leaderLine = false;
1837
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1838
                        if (symbolMapping != null)
1839
                            leaderLine = symbolMapping.LEADERLINE;
1840

    
1841
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1842
                        if (_LMLabelPresist != null)
1843
                        {
1844
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1845
                            _LMLabelPresist.Commit();
1846
                            ReleaseCOMObjects(_LMLabelPresist);
1847
                        }
1848
                        ReleaseCOMObjects(connectedLMConnector);
1849
                    }
1850

    
1851
                    foreach (var item in connectorVertices)
1852
                        if (item.Key != null)
1853
                            ReleaseCOMObjects(item.Key);
1854
                }
1855
            }
1856
        }
1857

    
1858
        /// <summary>
1859
        /// Equipment를 실제로 Modeling 메서드
1860
        /// </summary>
1861
        /// <param name="equipment"></param>
1862
        private void EquipmentModeling(Equipment equipment)
1863
        {
1864
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1865
                return;
1866

    
1867
            LMSymbol _LMSymbol = null;
1868
            LMSymbol targetItem = null;
1869
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1870
            double x = equipment.SPPID.ORIGINAL_X;
1871
            double y = equipment.SPPID.ORIGINAL_Y;
1872
            int mirror = 0;
1873
            double angle = equipment.ANGLE;
1874

    
1875
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1876

    
1877
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1878
            if (connector != null)
1879
            {
1880
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1881
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1882
                if (connEquipment != null)
1883
                {
1884
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1885
                        EquipmentModeling(connEquipment);
1886

    
1887
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1888
                    {
1889
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1890
                        if (targetItem != null)
1891
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1892
                        else
1893
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1894
                    }
1895
                    else
1896
                    {
1897
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1898
                    }
1899
                }
1900
                else if (connVendorPackage != null)
1901
                {
1902
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1903
                    {
1904
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1905
                        if (targetItem != null)
1906
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1907
                        else
1908
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1909
                    }
1910
                }
1911
                else
1912
                {
1913
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1914
                }
1915
            }
1916
            else
1917
            {
1918
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1919
            }
1920

    
1921
            if (_LMSymbol != null)
1922
            {
1923
                _LMSymbol.Commit();
1924
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1925
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1926
                ReleaseCOMObjects(_LMSymbol);
1927
            }
1928

    
1929
            if (targetItem != null)
1930
            {
1931
                ReleaseCOMObjects(targetItem);
1932
            }
1933

    
1934
            ReleaseCOMObjects(_LMSymbol);
1935
        }
1936

    
1937
        private void VendorPackageModeling(VendorPackage vendorPackage)
1938
        {
1939
            ETCSetting setting = ETCSetting.GetInstance();
1940
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1941
            {
1942
                string symbolPath = setting.VendorPackageSymbolPath;
1943
                double x = vendorPackage.SPPID.ORIGINAL_X;
1944
                double y = vendorPackage.SPPID.ORIGINAL_Y;
1945

    
1946
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
1947
                if (symbol != null)
1948
                {
1949
                    symbol.Commit();
1950
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
1951
                }
1952

    
1953
                ReleaseCOMObjects(symbol);
1954
                symbol = null;
1955
            }
1956
        }
1957

    
1958
        /// <summary>
1959
        /// 첫 진입점
1960
        /// </summary>
1961
        /// <param name="symbol"></param>
1962
        private void SymbolModelingBySymbol(Symbol symbol)
1963
        {
1964
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1965
            List<object> endObjects = new List<object>();
1966
            endObjects.Add(symbol);
1967

    
1968
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1969
            foreach (var connector in symbol.CONNECTORS)
1970
            {
1971
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1972
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1973
                {
1974
                    endObjects.Add(connItem);
1975
                    if (connItem.GetType() == typeof(Symbol))
1976
                    {
1977
                        Symbol connSymbol = connItem as Symbol;
1978
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1979
                        {
1980
                            SymbolModeling(connSymbol, symbol);
1981
                        }
1982
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1983
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1984
                    }
1985
                    else if (connItem.GetType() == typeof(Line))
1986
                    {
1987
                        Line connLine = connItem as Line;
1988
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1989
                    }
1990
                }
1991
            }
1992
        }
1993

    
1994
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1995
        {
1996
            foreach (var connector in symbol.CONNECTORS)
1997
            {
1998
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1999
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2000
                {
2001
                    if (!endObjects.Contains(connItem))
2002
                    {
2003
                        endObjects.Add(connItem);
2004
                        if (connItem.GetType() == typeof(Symbol))
2005
                        {
2006
                            Symbol connSymbol = connItem as Symbol;
2007
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2008
                            {
2009
                                SymbolModeling(connSymbol, symbol);
2010
                            }
2011
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2012
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2013
                        }
2014
                        else if (connItem.GetType() == typeof(Line))
2015
                        {
2016
                            Line connLine = connItem as Line;
2017
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2018
                        }
2019
                    }
2020
                }
2021
            }
2022
        }
2023

    
2024
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2025
        {
2026
            foreach (var connector in line.CONNECTORS)
2027
            {
2028
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2029
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2030
                {
2031
                    if (!endObjects.Contains(connItem))
2032
                    {
2033
                        endObjects.Add(connItem);
2034
                        if (connItem.GetType() == typeof(Symbol))
2035
                        {
2036
                            Symbol connSymbol = connItem as Symbol;
2037
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2038
                            {
2039
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2040
                                int branchCount = 0;
2041
                                if (connLine != null)
2042
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2043

    
2044
                                List<Symbol> group = new List<Symbol>();
2045
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2046
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2047
                                List<Symbol> endModelingGroup = new List<Symbol>();
2048
                                if (priority != null)
2049
                                {
2050
                                    SymbolGroupModeling(priority, group);
2051

    
2052
                                    // Range 겹치는지 확인해야함
2053
                                    double[] prevRange = null;
2054
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2055
                                    double[] groupRange = null;
2056
                                    GetSPPIDSymbolRange(group, ref groupRange);
2057

    
2058
                                    double distanceX = 0;
2059
                                    double distanceY = 0;
2060
                                    bool overlapX = false;
2061
                                    bool overlapY = false;
2062
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2063
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2064
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2065
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2066
                                    {
2067
                                        RemoveSymbol(group);
2068
                                        foreach (var _temp in group)
2069
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2070

    
2071
                                        SymbolGroupModeling(priority, group);
2072
                                    }
2073
                                    else if (branchCount > 0)
2074
                                    {
2075
                                        LMConnector _connector = JustLineModeling(connLine);
2076
                                        if (_connector != null)
2077
                                        {
2078
                                            double distance = GetConnectorDistance(_connector);
2079
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2080
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2081
                                            _connector.Commit();
2082
                                            ReleaseCOMObjects(_connector);
2083
                                            _connector = null;
2084
                                            if (cellCount < branchCount + 1)
2085
                                            {
2086
                                                int moveCount = branchCount - cellCount;
2087
                                                RemoveSymbol(group);
2088
                                                foreach (var _temp in group)
2089
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2090

    
2091
                                                SymbolGroupModeling(priority, group);
2092
                                            }
2093
                                        }
2094
                                    }
2095
                                }
2096
                                else
2097
                                {
2098
                                    SymbolModeling(connSymbol, null);
2099
                                    // Range 겹치는지 확인해야함
2100
                                    double[] prevRange = null;
2101
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2102
                                    double[] connRange = null;
2103
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2104

    
2105
                                    double distanceX = 0;
2106
                                    double distanceY = 0;
2107
                                    bool overlapX = false;
2108
                                    bool overlapY = false;
2109
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2110
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2111
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2112
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2113
                                    {
2114
                                        RemoveSymbol(connSymbol);
2115
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2116

    
2117
                                        SymbolModeling(connSymbol, null);
2118
                                    }
2119
                                    else if (branchCount > 0)
2120
                                    {
2121
                                        LMConnector _connector = JustLineModeling(connLine);
2122
                                        if (_connector != null)
2123
                                        {
2124
                                            double distance = GetConnectorDistance(_connector);
2125
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2126
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2127
                                            _connector.Commit();
2128
                                            ReleaseCOMObjects(_connector);
2129
                                            _connector = null;
2130
                                            if (cellCount < branchCount + 1)
2131
                                            {
2132
                                                int moveCount = branchCount - cellCount;
2133
                                                RemoveSymbol(group);
2134
                                                foreach (var _temp in group)
2135
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2136

    
2137
                                                SymbolGroupModeling(priority, group);
2138
                                            }
2139
                                        }
2140
                                    }
2141
                                }
2142
                            }
2143
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2144
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2145
                        }
2146
                        else if (connItem.GetType() == typeof(Line))
2147
                        {
2148
                            Line connLine = connItem as Line;
2149
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2150
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2151
                        }
2152
                    }
2153
                }
2154
            }
2155
        }
2156

    
2157
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2158
        {
2159
            List<Symbol> endModelingGroup = new List<Symbol>();
2160
            SymbolModeling(firstSymbol, null);
2161
            endModelingGroup.Add(firstSymbol);
2162
            while (endModelingGroup.Count != group.Count)
2163
            {
2164
                foreach (var _symbol in group)
2165
                {
2166
                    if (!endModelingGroup.Contains(_symbol))
2167
                    {
2168
                        foreach (var _connector in _symbol.CONNECTORS)
2169
                        {
2170
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2171
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2172
                            {
2173
                                SymbolModeling(_symbol, _connSymbol);
2174
                                endModelingGroup.Add(_symbol);
2175
                                break;
2176
                            }
2177
                        }
2178
                    }
2179
                }
2180
            }
2181
        }
2182

    
2183
        /// <summary>
2184
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2185
        /// </summary>
2186
        /// <param name="childSymbol"></param>
2187
        /// <param name="parentSymbol"></param>
2188
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2189
        {
2190
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2191
            double x1 = 0;
2192
            double x2 = 0;
2193
            double y1 = 0;
2194
            double y2 = 0;
2195
            symbol2d.Range(out x1, out y1, out x2, out y2);
2196

    
2197
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2198
            if (_LMSymbol != null)
2199
            {
2200
                _LMSymbol.Commit();
2201
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2202
                foreach (var item in childSymbol.ChildSymbols)
2203
                    CreateChildSymbol(item, _LMSymbol, parent);
2204
            }
2205

    
2206

    
2207
            ReleaseCOMObjects(_LMSymbol);
2208
        }
2209
        double index = 0;
2210
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2211
        {
2212
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2213
                return;
2214

    
2215
            List<Line> group = new List<Line>();
2216
            GetConnectedLineGroup(line, group);
2217
            LineCoordinateCorrection(group);
2218

    
2219
            foreach (var groupLine in group)
2220
            {
2221
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2222
                {
2223
                    BranchLines.Add(groupLine);
2224
                    continue;
2225
                }
2226

    
2227
                bool diagonal = false;
2228
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2229
                    diagonal = true;
2230
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2231
                LMSymbol _LMSymbolStart = null;
2232
                LMSymbol _LMSymbolEnd = null;
2233
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2234
                foreach (var connector in groupLine.CONNECTORS)
2235
                {
2236
                    double x = 0;
2237
                    double y = 0;
2238
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2239
                    if (connector.ConnectedObject == null)
2240
                    {
2241
                        placeRunInputs.AddPoint(x, y);
2242
                    }
2243
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2244
                    {
2245
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2246
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2247
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2248
                        {
2249
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2250
                            if (_LMSymbolStart != null)
2251
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2252
                            else
2253
                                placeRunInputs.AddPoint(x, y);
2254
                        }
2255
                        else
2256
                        {
2257
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2258
                            if (_LMSymbolEnd != null)
2259
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2260
                            else
2261
                                placeRunInputs.AddPoint(x, y);
2262
                        }
2263
                    }
2264
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2265
                    {
2266
                        Line targetLine = connector.ConnectedObject as Line;
2267
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2268
                        {
2269
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2270
                            if (targetConnector != null)
2271
                            {
2272
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2273
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2274
                            }
2275
                            else
2276
                            {
2277
                                placeRunInputs.AddPoint( x, y);
2278
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2279
                            }
2280
                        }
2281
                        else
2282
                        {
2283
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2284
                            {
2285
                                index += 0.01;
2286
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2287
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2288
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2289
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2290
                                else
2291
                                {
2292
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2293
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2294
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2295
                                    else
2296
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2297
                                }
2298
                            }
2299

    
2300
                            placeRunInputs.AddPoint(x, y);
2301

    
2302
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2303
                            {
2304
                                index += 0.01;
2305
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2306
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2307
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2308
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2309
                                else
2310
                                {
2311
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2312
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2313
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2314
                                    else
2315
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2316
                                }
2317
                            }
2318
                        }
2319
                    }
2320
                }
2321

    
2322
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2323
                if (_lMConnector != null)
2324
                {
2325
                    _lMConnector.Commit();
2326
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2327

    
2328
                    bool bRemodelingStart = false;
2329
                    if (_LMSymbolStart != null)
2330
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2331
                    bool bRemodelingEnd = false;
2332
                    if (_LMSymbolEnd != null)
2333
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2334

    
2335
                    if (bRemodelingStart || bRemodelingEnd)
2336
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2337

    
2338
                    FlowMarkModeling(groupLine);
2339
                    //LineNumberModelingOnlyOne(groupLine);
2340

    
2341
                    ReleaseCOMObjects(_lMConnector);
2342

    
2343
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2344
                    if (modelItem != null)
2345
                    {
2346
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2347
                        if (attribute != null)
2348
                            attribute.set_Value("End 1 is upstream (Inlet)");
2349
                        modelItem.Commit();
2350
                    }
2351
                    ReleaseCOMObjects(modelItem);
2352
                    modelItem = null;
2353
                }
2354
                else if (!isBranchModeling)
2355
                {
2356
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2357
                }
2358

    
2359
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2360
                x.ConnectedObject != null &&
2361
                x.ConnectedObject.GetType() == typeof(Line) &&
2362
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2363
                .Select(x => x.ConnectedObject)
2364
                .ToList();
2365

    
2366
                foreach (var item in removeLines)
2367
                    RemoveLineForModeling(item as Line);
2368

    
2369
                ReleaseCOMObjects(_LMAItem);
2370
                _LMAItem = null;
2371
                ReleaseCOMObjects(placeRunInputs);
2372
                placeRunInputs = null;
2373
                ReleaseCOMObjects(_LMSymbolStart);
2374
                _LMSymbolStart = null;
2375
                ReleaseCOMObjects(_LMSymbolEnd);
2376
                _LMSymbolEnd = null;
2377

    
2378
                if (isBranchModeling && BranchLines.Contains(groupLine))
2379
                    BranchLines.Remove(groupLine);
2380
            }
2381
        }
2382

    
2383
        private LMConnector JustLineModeling(Line line)
2384
        {
2385
            bool diagonal = false;
2386
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2387
                diagonal = true;
2388
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2389
            LMSymbol _LMSymbolStart = null;
2390
            LMSymbol _LMSymbolEnd = null;
2391
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2392
            foreach (var connector in line.CONNECTORS)
2393
            {
2394
                double x = 0;
2395
                double y = 0;
2396
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2397
                if (connector.ConnectedObject == null)
2398
                {
2399
                    placeRunInputs.AddPoint(x, y);
2400
                }
2401
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2402
                {
2403
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2404
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2405
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2406
                    {
2407
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2408
                        if (_LMSymbolStart != null)
2409
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2410
                        else
2411
                            placeRunInputs.AddPoint(x, y);
2412
                    }
2413
                    else
2414
                    {
2415
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2416
                        if (_LMSymbolEnd != null)
2417
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2418
                        else
2419
                            placeRunInputs.AddPoint(x, y);
2420
                    }
2421
                }
2422
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2423
                {
2424
                    Line targetLine = connector.ConnectedObject as Line;
2425
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2426
                    {
2427
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2428
                        if (targetConnector != null)
2429
                        {
2430
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2431
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2432
                        }
2433
                        else
2434
                        {
2435
                            placeRunInputs.AddPoint(x, y);
2436
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2437
                        }
2438
                    }
2439
                    else
2440
                        placeRunInputs.AddPoint(x, y);
2441
                }
2442
            }
2443

    
2444
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2445
            if (_lMConnector != null)
2446
                _lMConnector.Commit();
2447

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

    
2457
            return _lMConnector;
2458
        }
2459

    
2460
        private void RemoveLineForModeling(Line line)
2461
        {
2462
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2463
            if (modelItem != null)
2464
            {
2465
                foreach (LMRepresentation rep in modelItem.Representations)
2466
                {
2467
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2468
                    {
2469
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2470
                        dynamic OID = rep.get_GraphicOID().ToString();
2471
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2472
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2473
                        int verticesCount = lineStringGeometry.VertexCount;
2474
                        double[] vertices = null;
2475
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2476
                        for (int i = 0; i < verticesCount; i++)
2477
                        {
2478
                            double x = 0;
2479
                            double y = 0;
2480
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2481
                            if (verticesCount == 2 && (x < 0 || y < 0))
2482
                                _placement.PIDRemovePlacement(rep);
2483
                        }
2484
                        ReleaseCOMObjects(_LMConnector);
2485
                    }
2486
                }
2487

    
2488
                ReleaseCOMObjects(modelItem);
2489
            }
2490
        }
2491

    
2492
        private void RemoveLine(Line line)
2493
        {
2494
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2495
            if (modelItem != null)
2496
            {
2497
                foreach (LMRepresentation rep in modelItem.Representations)
2498
                {
2499
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2500
                        _placement.PIDRemovePlacement(rep);
2501
                }
2502
                ReleaseCOMObjects(modelItem);
2503
            }
2504
            line.SPPID.ModelItemId = null;
2505
        }
2506

    
2507
        private void GetConnectedLineGroup(Line line, List<Line> group)
2508
        {
2509
            if (!group.Contains(line))
2510
                group.Add(line);
2511
            foreach (var connector in line.CONNECTORS)
2512
            {
2513
                if (connector.ConnectedObject != null &&
2514
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2515
                    !group.Contains(connector.ConnectedObject) &&
2516
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2517
                {
2518
                    Line connLine = connector.ConnectedObject as Line;
2519
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2520
                    {
2521
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2522
                            group.Insert(0, connLine);
2523
                        else
2524
                            group.Add(connLine);
2525
                        GetConnectedLineGroup(connLine, group);
2526
                    }
2527
                }
2528
            }
2529
        }
2530

    
2531
        private void LineCoordinateCorrection(List<Line> group)
2532
        {
2533
            // 순서대로 전 Item 기준 정렬
2534
            LineCoordinateCorrectionByStart(group);
2535

    
2536
            // 역으로 심볼이 있을 경우 좌표 보정
2537
            LineCoordinateCorrectionForLastLine(group);
2538
        }
2539

    
2540
        private void LineCoordinateCorrectionByStart(List<Line> group)
2541
        {
2542
            for (int i = 0; i < group.Count; i++)
2543
            {
2544
                Line line = group[i];
2545
                if (i == 0)
2546
                {
2547
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2548
                    if (symbolConnector != null)
2549
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2550
                }
2551
                else if (i != 0)
2552
                {
2553
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2554
                }
2555
            }
2556
        }
2557

    
2558
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2559
        {
2560
            Line checkLine = group[group.Count - 1];
2561
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2562
            if (lastSymbolConnector != null)
2563
            {
2564
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2565
                for (int i = group.Count - 2; i >= 0; i--)
2566
                {
2567
                    Line line = group[i + 1];
2568
                    Line prevLine = group[i];
2569

    
2570
                    // 같으면 보정
2571
                    if (line.SlopeType == prevLine.SlopeType)
2572
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2573
                    else
2574
                    {
2575
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2576
                        {
2577
                            double prevX = 0;
2578
                            double prevY = 0;
2579
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2580
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2581

    
2582
                            double x = 0;
2583
                            double y = 0;
2584
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2585
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2586
                        }
2587
                        else if (line.SlopeType == SlopeType.VERTICAL)
2588
                        {
2589
                            double prevX = 0;
2590
                            double prevY = 0;
2591
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2592
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2593

    
2594
                            double x = 0;
2595
                            double y = 0;
2596
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2597
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2598
                        }
2599
                        break;
2600
                    }
2601
                }
2602
            }
2603
        }
2604

    
2605
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2606
        {
2607
            double x = 0;
2608
            double y = 0;
2609
            if (connItem.GetType() == typeof(Symbol))
2610
            {
2611
                Symbol targetSymbol = connItem as Symbol;
2612
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2613
                if (targetConnector != null)
2614
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2615
                else
2616
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2617
            }
2618
            else if (connItem.GetType() == typeof(Line))
2619
            {
2620
                Line targetLine = connItem as Line;
2621
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2622
            }
2623

    
2624
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2625
        }
2626

    
2627
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2628
        {
2629
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2630
            int index = line.CONNECTORS.IndexOf(connector);
2631
            if (index == 0)
2632
            {
2633
                line.SPPID.START_X = x;
2634
                line.SPPID.START_Y = y;
2635
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2636
                    line.SPPID.END_Y = y;
2637
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2638
                    line.SPPID.END_X = x;
2639
            }
2640
            else
2641
            {
2642
                line.SPPID.END_X = x;
2643
                line.SPPID.END_Y = y;
2644
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2645
                    line.SPPID.START_Y = y;
2646
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2647
                    line.SPPID.START_X = x;
2648
            }
2649
        }
2650

    
2651
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2652
        {
2653
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2654
            int index = line.CONNECTORS.IndexOf(connector);
2655
            if (index == 0)
2656
            {
2657
                line.SPPID.START_X = x;
2658
                if (line.SlopeType == SlopeType.VERTICAL)
2659
                    line.SPPID.END_X = x;
2660
            }
2661
            else
2662
            {
2663
                line.SPPID.END_X = x;
2664
                if (line.SlopeType == SlopeType.VERTICAL)
2665
                    line.SPPID.START_X = x;
2666
            }
2667
        }
2668

    
2669
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2670
        {
2671
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2672
            int index = line.CONNECTORS.IndexOf(connector);
2673
            if (index == 0)
2674
            {
2675
                line.SPPID.START_Y = y;
2676
                if (line.SlopeType == SlopeType.HORIZONTAL)
2677
                    line.SPPID.END_Y = y;
2678
            }
2679
            else
2680
            {
2681
                line.SPPID.END_Y = y;
2682
                if (line.SlopeType == SlopeType.HORIZONTAL)
2683
                    line.SPPID.START_Y = y;
2684
            }
2685
        }
2686

    
2687
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2688
        {
2689
            if (symbol != null)
2690
            {
2691
                string repID = symbol.AsLMRepresentation().Id;
2692
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2693
                string lineUID = line.UID;
2694

    
2695
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2696
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2697
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2698

    
2699
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2700
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2701
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2702

    
2703
                if (startSpecBreak != null || startEndBreak != null)
2704
                    result = true;
2705
            }
2706
        }
2707

    
2708
        /// <summary>
2709
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2710
        /// </summary>
2711
        /// <param name="lines"></param>
2712
        /// <param name="prevLMConnector"></param>
2713
        /// <param name="startSymbol"></param>
2714
        /// <param name="endSymbol"></param>
2715
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2716
        {
2717
            string symbolPath = string.Empty;
2718
            #region get symbol path
2719
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2720
            symbolPath = GetSPPIDFileName(modelItem);
2721
            ReleaseCOMObjects(modelItem);
2722
            #endregion
2723
            bool diagonal = false;
2724
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2725
                diagonal = true;
2726
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2727
            LMConnector newConnector = null;
2728
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2729
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2730
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2731
            int verticesCount = lineStringGeometry.VertexCount;
2732
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2733

    
2734
            List<double[]> vertices = new List<double[]>();
2735
            for (int i = 1; i <= verticesCount; i++)
2736
            {
2737
                double x = 0;
2738
                double y = 0;
2739
                lineStringGeometry.GetVertex(i, ref x, ref y);
2740
                vertices.Add(new double[] { x, y });
2741
            }
2742

    
2743
            for (int i = 0; i < vertices.Count; i++)
2744
            {
2745
                double[] points = vertices[i];
2746
                // 시작 심볼이 있고 첫번째 좌표일 때
2747
                if (startSymbol != null && i == 0)
2748
                {
2749
                    if (bStart)
2750
                    {
2751
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2752
                        if (slopeType == SlopeType.HORIZONTAL)
2753
                            placeRunInputs.AddPoint(points[0], -0.1);
2754
                        else if (slopeType == SlopeType.VERTICAL)
2755
                            placeRunInputs.AddPoint(-0.1, points[1]);
2756
                        else
2757
                            placeRunInputs.AddPoint(points[0], -0.1);
2758

    
2759
                        placeRunInputs.AddPoint(points[0], points[1]);
2760
                    }
2761
                    else
2762
                    {
2763
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2764
                    }
2765
                }
2766
                // 마지막 심볼이 있고 마지막 좌표일 때
2767
                else if (endSymbol != null && i == vertices.Count - 1)
2768
                {
2769
                    if (bEnd)
2770
                    {
2771
                        placeRunInputs.AddPoint(points[0], points[1]);
2772

    
2773
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2774
                        if (slopeType == SlopeType.HORIZONTAL)
2775
                            placeRunInputs.AddPoint(points[0], -0.1);
2776
                        else if (slopeType == SlopeType.VERTICAL)
2777
                            placeRunInputs.AddPoint(-0.1, points[1]);
2778
                        else
2779
                            placeRunInputs.AddPoint(points[0], -0.1);
2780
                    }
2781
                    else
2782
                    {
2783
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2784
                    }
2785
                }
2786
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2787
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2788
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2789
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2790
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2791
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2792
                else
2793
                    placeRunInputs.AddPoint(points[0], points[1]);
2794
            }
2795

    
2796
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2797
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2798

    
2799
            ReleaseCOMObjects(placeRunInputs);
2800
            ReleaseCOMObjects(_LMAItem);
2801
            ReleaseCOMObjects(modelItem);
2802

    
2803
            if (newConnector != null)
2804
            {
2805
                newConnector.Commit();
2806
                if (startSymbol != null && bStart)
2807
                {
2808
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2809
                    placeRunInputs = new PlaceRunInputs();
2810
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2811
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2812
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2813
                    if (_LMConnector != null)
2814
                    {
2815
                        _LMConnector.Commit();
2816
                        RemoveConnectorForReModelingLine(newConnector);
2817
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2818
                        ReleaseCOMObjects(_LMConnector);
2819
                    }
2820
                    ReleaseCOMObjects(placeRunInputs);
2821
                    ReleaseCOMObjects(_LMAItem);
2822
                }
2823

    
2824
                if (endSymbol != null && bEnd)
2825
                {
2826
                    if (startSymbol != null)
2827
                    {
2828
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2829
                        newConnector = dicVertices.First().Key;
2830
                    }
2831

    
2832
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2833
                    placeRunInputs = new PlaceRunInputs();
2834
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2835
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2836
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2837
                    if (_LMConnector != null)
2838
                    {
2839
                        _LMConnector.Commit();
2840
                        RemoveConnectorForReModelingLine(newConnector);
2841
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2842
                        ReleaseCOMObjects(_LMConnector);
2843
                    }
2844
                    ReleaseCOMObjects(placeRunInputs);
2845
                    ReleaseCOMObjects(_LMAItem);
2846
                }
2847

    
2848
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2849
                ReleaseCOMObjects(newConnector);
2850
            }
2851

    
2852
            ReleaseCOMObjects(modelItem);
2853
        }
2854

    
2855
        /// <summary>
2856
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2857
        /// </summary>
2858
        /// <param name="connector"></param>
2859
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2860
        {
2861
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2862
            foreach (var item in dicVertices)
2863
            {
2864
                if (item.Value.Count == 2)
2865
                {
2866
                    bool result = false;
2867
                    foreach (var point in item.Value)
2868
                    {
2869
                        if (point[0] < 0 || point[1] < 0)
2870
                        {
2871
                            result = true;
2872
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2873
                            break;
2874
                        }
2875
                    }
2876

    
2877
                    if (result)
2878
                        break;
2879
                }
2880
            }
2881
            foreach (var item in dicVertices)
2882
                ReleaseCOMObjects(item.Key);
2883
        }
2884

    
2885
        /// <summary>
2886
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2887
        /// </summary>
2888
        /// <param name="symbol"></param>
2889
        /// <param name="line"></param>
2890
        /// <returns></returns>
2891
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2892
        {
2893
            LMSymbol _LMSymbol = null;
2894
            foreach (var connector in symbol.CONNECTORS)
2895
            {
2896
                if (connector.CONNECTEDITEM == line.UID)
2897
                {
2898
                    if (connector.Index == 0)
2899
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2900
                    else
2901
                    {
2902
                        ChildSymbol child = null;
2903
                        foreach (var childSymbol in symbol.ChildSymbols)
2904
                        {
2905
                            if (childSymbol.Connectors.Contains(connector))
2906
                                child = childSymbol;
2907
                            else
2908
                                child = GetChildSymbolByConnector(childSymbol, connector);
2909

    
2910
                            if (child != null)
2911
                                break;
2912
                        }
2913

    
2914
                        if (child != null)
2915
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2916
                    }
2917

    
2918
                    break;
2919
                }
2920
            }
2921

    
2922
            return _LMSymbol;
2923
        }
2924

    
2925
        /// <summary>
2926
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2927
        /// </summary>
2928
        /// <param name="item"></param>
2929
        /// <param name="connector"></param>
2930
        /// <returns></returns>
2931
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2932
        {
2933
            foreach (var childSymbol in item.ChildSymbols)
2934
            {
2935
                if (childSymbol.Connectors.Contains(connector))
2936
                    return childSymbol;
2937
                else
2938
                    return GetChildSymbolByConnector(childSymbol, connector);
2939
            }
2940

    
2941
            return null;
2942
        }
2943

    
2944
        /// <summary>
2945
        /// EndBreak 모델링 메서드
2946
        /// </summary>
2947
        /// <param name="endBreak"></param>
2948
        private void EndBreakModeling(EndBreak endBreak)
2949
        {
2950
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2951
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2952

    
2953
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2954
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2955
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2956

    
2957
            if (targetLMConnector != null)
2958
            {
2959
                // LEADER Line 검사
2960
                bool leaderLine = false;
2961
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
2962
                if (symbolMapping != null)
2963
                    leaderLine = symbolMapping.LEADERLINE;
2964

    
2965
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2966
                Array array = null;
2967
                if (point != null)
2968
                    array = new double[] { 0, point[0], point[1] };
2969
                else
2970
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2971
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
2972
                if (_LmLabelPersist != null)
2973
                {
2974
                    _LmLabelPersist.Commit();
2975
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2976
                    if (_LmLabelPersist.ModelItemObject != null)
2977
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2978
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2979
                    ReleaseCOMObjects(_LmLabelPersist);
2980
                }
2981
                ReleaseCOMObjects(targetLMConnector);
2982
            }
2983
            else
2984
            {
2985
                Log.Write("End Break UID : " + endBreak.UID);
2986
                Log.Write("Can't find targetLMConnector");
2987
            }
2988
        }
2989

    
2990
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2991
        {
2992
            string symbolPath = string.Empty;
2993
            #region get symbol path
2994
            if (string.IsNullOrEmpty(changeSymbolPath))
2995
            {
2996
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2997
                symbolPath = GetSPPIDFileName(modelItem);
2998
                ReleaseCOMObjects(modelItem);
2999
            }
3000
            else
3001
                symbolPath = changeSymbolPath;
3002
            
3003
            #endregion
3004

    
3005
            LMConnector newConnector = null;
3006
            dynamic OID = connector.get_GraphicOID().ToString();
3007
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3008
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3009
            int verticesCount = lineStringGeometry.VertexCount;
3010
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3011
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3012

    
3013
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3014
            {
3015
                double[] vertices = null;
3016
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3017
                double x = 0;
3018
                double y = 0;
3019
                lineStringGeometry.GetVertex(1, ref x, ref y);
3020

    
3021
                string flowDirection = string.Empty;
3022
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3023
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3024
                    flowDirection = flowAttribute.get_Value().ToString();
3025

    
3026
                if (flowDirection == "End 1 is downstream (Outlet)")
3027
                {
3028
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3029
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3030
                    flowDirection = "End 1 is upstream (Inlet)";
3031
                }
3032
                else
3033
                {
3034
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3035
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3036
                }
3037
                string oldModelItemId = connector.ModelItemID;
3038
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3039
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3040
                newConnector.Commit();
3041
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3042
                if (!string.IsNullOrEmpty(flowDirection))
3043
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3044
                ReleaseCOMObjects(connector);
3045

    
3046
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3047
                {
3048
                    foreach (var repId in line.SPPID.Representations)
3049
                    {
3050
                        LMConnector _connector = dataSource.GetConnector(repId);
3051
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3052
                        {
3053
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3054
                            {
3055
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3056
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3057
                            }
3058
                        }
3059
                        ReleaseCOMObjects(_connector);
3060
                        _connector = null;
3061
                    }
3062
                }
3063
            }
3064

    
3065
            return newConnector;
3066
        }
3067

    
3068
        /// <summary>
3069
        /// SpecBreak Modeling 메서드
3070
        /// </summary>
3071
        /// <param name="specBreak"></param>
3072
        private void SpecBreakModeling(SpecBreak specBreak)
3073
        {
3074
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3075
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3076

    
3077
            if (upStreamObj != null &&
3078
                downStreamObj != null)
3079
            {
3080
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3081
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3082
                    targetLMConnector != null && 
3083
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3084
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3085

    
3086
                if (targetLMConnector != null)
3087
                {
3088
                    foreach (var attribute in specBreak.ATTRIBUTES)
3089
                    {
3090
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3091
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3092
                        {
3093
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3094
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
3095
                            Array array = null;
3096
                            if (point != null)
3097
                                array = new double[] { 0, point[0], point[1] };
3098
                            else
3099
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3100
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3101

    
3102
                            if (_LmLabelPersist != null)
3103
                            {
3104
                                _LmLabelPersist.Commit();
3105
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3106
                                if (_LmLabelPersist.ModelItemObject != null)
3107
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3108
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3109
                                ReleaseCOMObjects(_LmLabelPersist);
3110
                            }
3111

    
3112
                            // temp
3113
                            ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3114
                        }
3115
                    }
3116
                    ReleaseCOMObjects(targetLMConnector);
3117
                }
3118
                else
3119
                {
3120
                    Log.Write("Spec Break UID : " + specBreak.UID);
3121
                    Log.Write("Can't find targetLMConnector");
3122
                }
3123
            }
3124
        }
3125

    
3126
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3127
        {
3128
            LMConnector targetConnector = null;
3129
            Symbol targetSymbol = targetObj as Symbol;
3130
            Symbol connectedSymbol = connectedObj as Symbol;
3131
            Line targetLine = targetObj as Line;
3132
            Line connectedLine = connectedObj as Line;
3133
            if (targetSymbol != null && connectedSymbol != null)
3134
            {
3135
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3136
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3137

    
3138
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3139
                {
3140
                    if (connector.get_ItemStatus() != "Active")
3141
                        continue;
3142

    
3143
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3144
                    {
3145
                        targetConnector = connector;
3146
                        break;
3147
                    }
3148
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3149
                    {
3150
                        targetConnector = connector;
3151
                        break;
3152
                    }
3153
                }
3154

    
3155
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3156
                {
3157
                    if (connector.get_ItemStatus() != "Active")
3158
                        continue;
3159

    
3160
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3161
                    {
3162
                        targetConnector = connector;
3163
                        break;
3164
                    }
3165
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3166
                    {
3167
                        targetConnector = connector;
3168
                        break;
3169
                    }
3170
                }
3171

    
3172
                ReleaseCOMObjects(targetLMSymbol);
3173
                ReleaseCOMObjects(connectedLMSymbol);
3174
            }
3175
            else if (targetLine != null && connectedLine != null)
3176
            {
3177
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3178
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3179

    
3180
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3181
                {
3182
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3183
                    {
3184
                        if (targetConnector != null)
3185
                            break;
3186

    
3187
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3188
                        {
3189
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3190

    
3191
                            if (IsConnected(_LMConnector, connectedModelItem))
3192
                                targetConnector = _LMConnector;
3193
                            else
3194
                                ReleaseCOMObjects(_LMConnector);
3195
                        }
3196
                    }
3197

    
3198
                    ReleaseCOMObjects(targetModelItem);
3199
                }
3200
            }
3201
            else
3202
            {
3203
                LMSymbol connectedLMSymbol = null;
3204
                if (connectedSymbol != null)
3205
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3206
                else if (targetSymbol != null)
3207
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3208
                else
3209
                {
3210

    
3211
                }
3212
                LMModelItem targetModelItem = null;
3213
                if (targetLine != null)
3214
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3215
                else if (connectedLine != null)
3216
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3217
                else
3218
                {
3219

    
3220
                }
3221
                if (connectedLMSymbol != null && targetModelItem != null)
3222
                {
3223
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3224
                    {
3225
                        if (connector.get_ItemStatus() != "Active")
3226
                            continue;
3227

    
3228
                        if (IsConnected(connector, targetModelItem))
3229
                        {
3230
                            targetConnector = connector;
3231
                            break;
3232
                        }
3233
                    }
3234

    
3235
                    if (targetConnector == null)
3236
                    {
3237
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3238
                        {
3239
                            if (connector.get_ItemStatus() != "Active")
3240
                                continue;
3241

    
3242
                            if (IsConnected(connector, targetModelItem))
3243
                            {
3244
                                targetConnector = connector;
3245
                                break;
3246
                            }
3247
                        }
3248
                    }
3249
                }
3250

    
3251
            }
3252

    
3253
            return targetConnector;
3254
        }
3255

    
3256
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3257
        {
3258
            double[] result = null;
3259
            Line targetLine = targetObj as Line;
3260
            Symbol targetSymbol = targetObj as Symbol;
3261
            Line connLine = connObj as Line;
3262
            Symbol connSymbol = connObj as Symbol;
3263

    
3264
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
3265
            double lineMove = GridSetting.GetInstance().Length * 3;
3266
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3267
            {
3268
                result = GetConnectorVertices(targetConnector)[0];
3269
                if (targetSymbol != null && connSymbol != null)
3270
                {
3271
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3272
                    if (slopeType == SlopeType.HORIZONTAL)
3273
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3274
                    else if (slopeType == SlopeType.VERTICAL)
3275
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3276
                }
3277
                else if (targetLine != null)
3278
                {
3279
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3280
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3281
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3282
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3283
                }
3284
                else if (connLine != null)
3285
                {
3286
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3287
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3288
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3289
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3290
                }
3291
            }
3292
            else
3293
            {
3294
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3295
                {
3296
                    Line line = connObj as Line;
3297
                    LMConnector connectedConnector = null;
3298
                    int connIndex = 0;
3299
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3300
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3301

    
3302
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3303

    
3304
                    ReleaseCOMObjects(modelItem);
3305
                    ReleaseCOMObjects(connectedConnector);
3306

    
3307
                    if (vertices.Count > 0)
3308
                    {
3309
                        if (connIndex == 1)
3310
                            result = vertices[0];
3311
                        else if (connIndex == 2)
3312
                            result = vertices[vertices.Count - 1];
3313

    
3314
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3315
                        {
3316
                            result = new double[] { result[0], result[1] - lineMove };
3317
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3318
                            {
3319
                                result = new double[] { result[0] - lineMove, result[1] };
3320
                            }
3321
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3322
                            {
3323
                                result = new double[] { result[0] + lineMove, result[1] };
3324
                            }
3325
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3326
                            {
3327
                                result = new double[] { result[0] + lineMove, result[1] };
3328
                            }
3329
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3330
                            {
3331
                                result = new double[] { result[0] - lineMove, result[1] };
3332
                            }
3333
                        }
3334
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3335
                        {
3336
                            result = new double[] { result[0] - lineMove, result[1] };
3337
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3338
                            {
3339
                                result = new double[] { result[0], result[1] - lineMove };
3340
                            }
3341
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3342
                            {
3343
                                result = new double[] { result[0], result[1] + lineMove };
3344
                            }
3345
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3346
                            {
3347
                                result = new double[] { result[0], result[1] + lineMove };
3348
                            }
3349
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3350
                            {
3351
                                result = new double[] { result[0], result[1] - lineMove };
3352
                            }
3353
                        }
3354
                            
3355
                    }
3356
                }
3357
                else
3358
                {
3359
                    Log.Write("error in GetSegemtPoint");
3360
                }
3361
            }
3362

    
3363
            return result;
3364
        }
3365

    
3366
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3367
        {
3368
            bool result = false;
3369

    
3370
            foreach (LMRepresentation rep in modelItem.Representations)
3371
            {
3372
                if (result)
3373
                    break;
3374

    
3375
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3376
                {
3377
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3378

    
3379
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3380
                        connector.ConnectItem1SymbolObject != null &&
3381
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3382
                    {
3383
                        result = true;
3384
                        ReleaseCOMObjects(_LMConnector);
3385
                        break;
3386
                    }
3387
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3388
                        connector.ConnectItem2SymbolObject != null &&
3389
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3390
                    {
3391
                        result = true;
3392
                        ReleaseCOMObjects(_LMConnector);
3393
                        break;
3394
                    }
3395
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3396
                        connector.ConnectItem1SymbolObject != null &&
3397
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3398
                    {
3399
                        result = true;
3400
                        ReleaseCOMObjects(_LMConnector);
3401
                        break;
3402
                    }
3403
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3404
                        connector.ConnectItem2SymbolObject != null &&
3405
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3406
                    {
3407
                        result = true;
3408
                        ReleaseCOMObjects(_LMConnector);
3409
                        break;
3410
                    }
3411

    
3412
                    ReleaseCOMObjects(_LMConnector);
3413
                }
3414
            }
3415

    
3416

    
3417
            return result;
3418
        }
3419

    
3420
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3421
        {
3422
            foreach (LMRepresentation rep in modelItem.Representations)
3423
            {
3424
                if (connectedConnector != null)
3425
                    break;
3426

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

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

    
3464
                    if (connectedConnector == null)
3465
                        ReleaseCOMObjects(_LMConnector);
3466
                }
3467
            }
3468
        }
3469

    
3470
        /// <summary>
3471
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3472
        /// </summary>
3473
        /// <param name="modelItemID1"></param>
3474
        /// <param name="modelItemID2"></param>
3475
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3476
        {
3477
            try
3478
            {
3479
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3480
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3481
                List<double[]> vertices1 = null;
3482
                string graphicOID1 = string.Empty;
3483
                if (connector1 != null)
3484
                {
3485
                    vertices1 = GetConnectorVertices(connector1);
3486
                    graphicOID1 = connector1.get_GraphicOID();
3487
                }
3488
                _LMAItem item1 = modelItem1.AsLMAItem();
3489
                ReleaseCOMObjects(connector1);
3490
                connector1 = null;
3491

    
3492
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3493
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3494
                List<double[]> vertices2 = null;
3495
                string graphicOID2 = string.Empty;
3496
                if (connector2 != null)
3497
                {
3498
                    vertices2 = GetConnectorVertices(connector2);
3499
                    graphicOID2 = connector2.get_GraphicOID();
3500
                }
3501
                _LMAItem item2 = modelItem2.AsLMAItem();
3502
                ReleaseCOMObjects(connector2);
3503
                connector2 = null;
3504

    
3505
                // item2가 item1으로 조인
3506
                _placement.PIDJoinRuns(ref item1, ref item2);
3507
                item1.Commit();
3508
                item2.Commit();
3509

    
3510
                string beforeID = string.Empty;
3511
                string afterID = string.Empty;
3512

    
3513
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3514
                {
3515
                    beforeID = modelItem2.Id;
3516
                    afterID = modelItem1.Id;
3517
                    survivorId = afterID;
3518
                }
3519
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3520
                {
3521
                    beforeID = modelItem1.Id;
3522
                    afterID = modelItem2.Id;
3523
                    survivorId = afterID;
3524
                }
3525
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3526
                {
3527
                    int model1Cnt = GetConnectorCount(modelId1);
3528
                    int model2Cnt = GetConnectorCount(modelId2);
3529
                    if (model1Cnt == 0)
3530
                    {
3531
                        beforeID = modelItem1.Id;
3532
                        afterID = modelItem2.Id;
3533
                        survivorId = afterID;
3534
                    }
3535
                    else if (model2Cnt == 0)
3536
                    {
3537
                        beforeID = modelItem2.Id;
3538
                        afterID = modelItem1.Id;
3539
                        survivorId = afterID;
3540
                    }
3541
                    else
3542
                        survivorId = null;
3543
                }
3544
                else
3545
                {
3546
                    Log.Write("잘못된 경우");
3547
                    survivorId = null;
3548
                }
3549

    
3550
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3551
                {
3552
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3553
                    foreach (var line in lines)
3554
                        line.SPPID.ModelItemId = afterID;
3555
                }
3556

    
3557
                ReleaseCOMObjects(modelItem1);
3558
                ReleaseCOMObjects(item1);
3559
                ReleaseCOMObjects(modelItem2);
3560
                ReleaseCOMObjects(item2);
3561
            }
3562
            catch (Exception ex)
3563
            {
3564
                Log.Write("Join Error");
3565
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3566
            }
3567
        }
3568

    
3569
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3570
        {
3571
            bool result = false;
3572
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3573
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3574
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3575

    
3576
            foreach (var item in endBreaks)
3577
            {
3578
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3579
                {
3580
                    result = true;
3581
                    break;
3582
                }
3583
            }
3584

    
3585
            return result;
3586
        }
3587
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3588
        {
3589
            List<string> temp = new List<string>();
3590
            List<LMConnector> connectors = new List<LMConnector>();
3591
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3592
            {
3593
                if (connector.get_ItemStatus() != "Active")
3594
                    continue;
3595

    
3596
                LMModelItem modelItem = connector.ModelItemObject;
3597
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3598
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3599
                    temp.Add(modelItem.Id);
3600

    
3601
                if (temp.Contains(modelItem.Id) &&
3602
                    connOtherSymbol != null &&
3603
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3604
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3605
                    temp.Remove(modelItem.Id);
3606

    
3607

    
3608
                if (temp.Contains(modelItem.Id))
3609
                    connectors.Add(connector);
3610
                ReleaseCOMObjects(connOtherSymbol);
3611
                connOtherSymbol = null;
3612
                ReleaseCOMObjects(modelItem);
3613
                modelItem = null;
3614
            }
3615

    
3616
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3617
            {
3618
                if (connector.get_ItemStatus() != "Active")
3619
                    continue;
3620

    
3621
                LMModelItem modelItem = connector.ModelItemObject;
3622
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3623
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3624
                    temp.Add(modelItem.Id);
3625

    
3626
                if (temp.Contains(modelItem.Id) &&
3627
                    connOtherSymbol != null &&
3628
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3629
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3630
                    temp.Remove(modelItem.Id);
3631

    
3632
                if (temp.Contains(modelItem.Id))
3633
                    connectors.Add(connector);
3634
                ReleaseCOMObjects(connOtherSymbol);
3635
                connOtherSymbol = null;
3636
                ReleaseCOMObjects(modelItem);
3637
                modelItem = null;
3638
            }
3639

    
3640

    
3641
            List<string> result = new List<string>();
3642
            string originalName = GetSPPIDFileName(modelId);
3643
            foreach (var connector in connectors)
3644
            {
3645
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3646
                if (originalName == fileName)
3647
                    result.Add(connector.ModelItemID);
3648
                else
3649
                {
3650
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3651
                        result.Add(connector.ModelItemID);
3652
                    else
3653
                    {
3654
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3655
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3656
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3657
                            result.Add(connector.ModelItemID);
3658
                    }
3659
                }
3660
            }
3661

    
3662
            foreach (var connector in connectors)
3663
                ReleaseCOMObjects(connector);
3664
            
3665
            return result;
3666

    
3667

    
3668
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3669
            {
3670
                LMSymbol findResult = null;
3671
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3672
                    findResult = connector.ConnectItem1SymbolObject;
3673
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3674
                    findResult = connector.ConnectItem2SymbolObject;
3675

    
3676
                return findResult;
3677
            }
3678
        }
3679

    
3680
        /// <summary>
3681
        /// PipeRun의 좌표를 가져오는 메서드
3682
        /// </summary>
3683
        /// <param name="modelId"></param>
3684
        /// <returns></returns>
3685
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3686
        {
3687
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3688
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3689

    
3690
            if (modelItem != null)
3691
            {
3692
                foreach (LMRepresentation rep in modelItem.Representations)
3693
                {
3694
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3695
                    {
3696
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3697
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3698
                        {
3699
                            ReleaseCOMObjects(_LMConnector);
3700
                            _LMConnector = null;
3701
                            continue;
3702
                        }
3703
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3704
                        dynamic OID = rep.get_GraphicOID().ToString();
3705
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3706
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3707
                        int verticesCount = lineStringGeometry.VertexCount;
3708
                        double[] vertices = null;
3709
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3710
                        for (int i = 0; i < verticesCount; i++)
3711
                        {
3712
                            double x = 0;
3713
                            double y = 0;
3714
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3715
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3716
                        }
3717
                    }
3718
                }
3719

    
3720
                ReleaseCOMObjects(modelItem);
3721
            }
3722

    
3723
            return connectorVertices;
3724
        }
3725

    
3726
        private List<double[]> GetConnectorVertices(LMConnector connector)
3727
        {
3728
            List<double[]> vertices = new List<double[]>();
3729
            if (connector != null)
3730
            {
3731
                dynamic OID = connector.get_GraphicOID().ToString();
3732
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3733
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3734
                int verticesCount = lineStringGeometry.VertexCount;
3735
                double[] value = null;
3736
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3737
                for (int i = 0; i < verticesCount; i++)
3738
                {
3739
                    double x = 0;
3740
                    double y = 0;
3741
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3742
                    vertices.Add(new double[] { x, y });
3743
                }
3744
            }
3745
            return vertices;
3746
        }
3747

    
3748
        private double GetConnectorDistance(LMConnector connector)
3749
        {
3750
            double result = 0;
3751
            List<double[]> vertices = new List<double[]>();
3752
            if (connector != null)
3753
            {
3754
                dynamic OID = connector.get_GraphicOID().ToString();
3755
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3756
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3757
                int verticesCount = lineStringGeometry.VertexCount;
3758
                double[] value = null;
3759
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3760
                for (int i = 0; i < verticesCount; i++)
3761
                {
3762
                    double x = 0;
3763
                    double y = 0;
3764
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3765
                    vertices.Add(new double[] { x, y });
3766
                    if (vertices.Count > 1)
3767
                    {
3768
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3769
                    }
3770
                }
3771
            }
3772
            return result;
3773
        }
3774
        private double[] GetConnectorRange(LMConnector connector)
3775
        {
3776
            double[] result = null;
3777
            List<double[]> vertices = new List<double[]>();
3778
            if (connector != null)
3779
            {
3780
                dynamic OID = connector.get_GraphicOID().ToString();
3781
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3782
                double minX = 0;
3783
                double minY = 0;
3784
                double maxX = 0;
3785
                double maxY = 0;
3786

    
3787
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
3788
                result = new double[] { minX, minY, maxX, maxY };
3789
            }
3790
            return result;
3791
        }
3792
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3793
        {
3794
            List<double[]> vertices = null;
3795
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3796
            if (drawingObject != null)
3797
            {
3798
                vertices = new List<double[]>();
3799
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3800
                int verticesCount = lineStringGeometry.VertexCount;
3801
                double[] value = null;
3802
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3803
                for (int i = 0; i < verticesCount; i++)
3804
                {
3805
                    double x = 0;
3806
                    double y = 0;
3807
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3808
                    vertices.Add(new double[] { x, y });
3809
                }
3810
            }
3811
            return vertices;
3812
        }
3813
        /// <summary>
3814
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3815
        /// </summary>
3816
        /// <param name="connectorVertices"></param>
3817
        /// <param name="connX"></param>
3818
        /// <param name="connY"></param>
3819
        /// <returns></returns>
3820
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3821
        {
3822
            double length = double.MaxValue;
3823
            LMConnector targetConnector = null;
3824
            foreach (var item in connectorVertices)
3825
            {
3826
                List<double[]> points = item.Value;
3827
                for (int i = 0; i < points.Count - 1; i++)
3828
                {
3829
                    double[] point1 = points[i];
3830
                    double[] point2 = points[i + 1];
3831
                    double x1 = Math.Min(point1[0], point2[0]);
3832
                    double y1 = Math.Min(point1[1], point2[1]);
3833
                    double x2 = Math.Max(point1[0], point2[0]);
3834
                    double y2 = Math.Max(point1[1], point2[1]);
3835

    
3836
                    if ((x1 <= connX && x2 >= connX) ||
3837
                        (y1 <= connY && y2 >= connY))
3838
                    {
3839
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3840
                        if (length >= distance)
3841
                        {
3842
                            targetConnector = item.Key;
3843
                            length = distance;
3844
                        }
3845

    
3846
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3847
                        if (length >= distance)
3848
                        {
3849
                            targetConnector = item.Key;
3850
                            length = distance;
3851
                        }
3852
                    }
3853
                }
3854
            }
3855

    
3856
            // 못찾았을때.
3857
            length = double.MaxValue;
3858
            if (targetConnector == null)
3859
            {
3860
                foreach (var item in connectorVertices)
3861
                {
3862
                    List<double[]> points = item.Value;
3863

    
3864
                    foreach (double[] point in points)
3865
                    {
3866
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3867
                        if (length >= distance)
3868
                        {
3869
                            targetConnector = item.Key;
3870
                            length = distance;
3871
                        }
3872
                    }
3873
                }
3874
            }
3875

    
3876
            return targetConnector;
3877
        }
3878

    
3879
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3880
        {
3881
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3882
            if (vertices.Count == 0)
3883
                return null;
3884

    
3885
            double length = double.MaxValue;
3886
            LMConnector targetConnector = null;
3887
            double[] resultPoint = null;
3888
            List<double[]> targetVertices = null;
3889

    
3890
            // Vertices 포인트에 제일 가까운곳
3891
            foreach (var item in vertices)
3892
            {
3893
                List<double[]> points = item.Value;
3894
                for (int i = 0; i < points.Count; i++)
3895
                {
3896
                    double[] point = points[i];
3897
                    double tempX = point[0];
3898
                    double tempY = point[1];
3899

    
3900
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3901
                    if (length >= distance)
3902
                    {
3903
                        targetConnector = item.Key;
3904
                        length = distance;
3905
                        resultPoint = point;
3906
                        targetVertices = item.Value;
3907
                    }
3908
                }
3909
            }
3910

    
3911
            // Vertices Cross에 제일 가까운곳
3912
            foreach (var item in vertices)
3913
            {
3914
                List<double[]> points = item.Value;
3915
                for (int i = 0; i < points.Count - 1; i++)
3916
                {
3917
                    double[] point1 = points[i];
3918
                    double[] point2 = points[i + 1];
3919

    
3920
                    double maxLineX = Math.Max(point1[0], point2[0]);
3921
                    double minLineX = Math.Min(point1[0], point2[0]);
3922
                    double maxLineY = Math.Max(point1[1], point2[1]);
3923
                    double minLineY = Math.Min(point1[1], point2[1]);
3924

    
3925
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3926

    
3927
                    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]);
3928
                    if (crossingPoint != null)
3929
                    {
3930
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3931
                        if (length >= distance)
3932
                        {
3933
                            if (slope == SlopeType.Slope &&
3934
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3935
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3936
                            {
3937
                                targetConnector = item.Key;
3938
                                length = distance;
3939
                                resultPoint = crossingPoint;
3940
                                targetVertices = item.Value;
3941
                            }
3942
                            else if (slope == SlopeType.HORIZONTAL &&
3943
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3944
                            {
3945
                                targetConnector = item.Key;
3946
                                length = distance;
3947
                                resultPoint = crossingPoint;
3948
                                targetVertices = item.Value;
3949
                            }
3950
                            else if (slope == SlopeType.VERTICAL &&
3951
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3952
                            {
3953
                                targetConnector = item.Key;
3954
                                length = distance;
3955
                                resultPoint = crossingPoint;
3956
                                targetVertices = item.Value;
3957
                            }
3958
                        }
3959
                    }
3960
                }
3961
            }
3962

    
3963
            foreach (var item in vertices)
3964
                if (item.Key != null && item.Key != targetConnector)
3965
                    ReleaseCOMObjects(item.Key);
3966

    
3967
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3968
            {
3969
                double tempResultX = resultPoint[0];
3970
                double tempResultY = resultPoint[1];
3971
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3972

    
3973
                GridSetting gridSetting = GridSetting.GetInstance();
3974

    
3975
                for (int i = 0; i < targetVertices.Count; i++)
3976
                {
3977
                    double[] point = targetVertices[i];
3978
                    double tempX = targetVertices[i][0];
3979
                    double tempY = targetVertices[i][1];
3980
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3981
                    if (tempX == tempResultX && tempY == tempResultY)
3982
                    {
3983
                        if (i == 0)
3984
                        {
3985
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3986
                            bool containZeroLength = false;
3987
                            if (connSymbol != null)
3988
                            {
3989
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3990
                                {
3991
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3992
                                        containZeroLength = true;
3993
                                }
3994
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3995
                                {
3996
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3997
                                        containZeroLength = true;
3998
                                }
3999
                            }
4000

    
4001
                            if (connSymbol == null ||
4002
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4003
                                containZeroLength)
4004
                            {
4005
                                bool bCalcX = false;
4006
                                bool bCalcY = false;
4007
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4008
                                    bCalcX = true;
4009
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4010
                                    bCalcY = true;
4011
                                else
4012
                                {
4013
                                    bCalcX = true;
4014
                                    bCalcY = true;
4015
                                }
4016

    
4017
                                if (bCalcX)
4018
                                {
4019
                                    double nextX = targetVertices[i + 1][0];
4020
                                    double newX = 0;
4021
                                    if (nextX > tempX)
4022
                                    {
4023
                                        newX = tempX + gridSetting.Length;
4024
                                        if (newX > nextX)
4025
                                            newX = (point[0] + nextX) / 2;
4026
                                    }
4027
                                    else
4028
                                    {
4029
                                        newX = tempX - gridSetting.Length;
4030
                                        if (newX < nextX)
4031
                                            newX = (point[0] + nextX) / 2;
4032
                                    }
4033
                                    resultPoint = new double[] { newX, resultPoint[1] };
4034
                                }
4035

    
4036
                                if (bCalcY)
4037
                                {
4038
                                    double nextY = targetVertices[i + 1][1];
4039
                                    double newY = 0;
4040
                                    if (nextY > tempY)
4041
                                    {
4042
                                        newY = tempY + gridSetting.Length;
4043
                                        if (newY > nextY)
4044
                                            newY = (point[1] + nextY) / 2;
4045
                                    }
4046
                                    else
4047
                                    {
4048
                                        newY = tempY - gridSetting.Length;
4049
                                        if (newY < nextY)
4050
                                            newY = (point[1] + nextY) / 2;
4051
                                    }
4052
                                    resultPoint = new double[] { resultPoint[0], newY };
4053
                                }
4054
                            }
4055
                        }
4056
                        else if (i == targetVertices.Count - 1)
4057
                        {
4058
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4059
                            bool containZeroLength = false;
4060
                            if (connSymbol != null)
4061
                            {
4062
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4063
                                {
4064
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4065
                                        containZeroLength = true;
4066
                                }
4067
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4068
                                {
4069
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4070
                                        containZeroLength = true;
4071
                                }
4072
                            }
4073

    
4074
                            if (connSymbol == null ||
4075
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4076
                                containZeroLength)
4077
                            {
4078
                                bool bCalcX = false;
4079
                                bool bCalcY = false;
4080
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4081
                                    bCalcX = true;
4082
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4083
                                    bCalcY = true;
4084
                                else
4085
                                {
4086
                                    bCalcX = true;
4087
                                    bCalcY = true;
4088
                                }
4089

    
4090
                                if (bCalcX)
4091
                                {
4092
                                    double nextX = targetVertices[i - 1][0];
4093
                                    double newX = 0;
4094
                                    if (nextX > tempX)
4095
                                    {
4096
                                        newX = tempX + gridSetting.Length;
4097
                                        if (newX > nextX)
4098
                                            newX = (point[0] + nextX) / 2;
4099
                                    }
4100
                                    else
4101
                                    {
4102
                                        newX = tempX - gridSetting.Length;
4103
                                        if (newX < nextX)
4104
                                            newX = (point[0] + nextX) / 2;
4105
                                    }
4106
                                    resultPoint = new double[] { newX, resultPoint[1] };
4107
                                }
4108

    
4109
                                if (bCalcY)
4110
                                {
4111
                                    double nextY = targetVertices[i - 1][1];
4112
                                    double newY = 0;
4113
                                    if (nextY > tempY)
4114
                                    {
4115
                                        newY = tempY + gridSetting.Length;
4116
                                        if (newY > nextY)
4117
                                            newY = (point[1] + nextY) / 2;
4118
                                    }
4119
                                    else
4120
                                    {
4121
                                        newY = tempY - gridSetting.Length;
4122
                                        if (newY < nextY)
4123
                                            newY = (point[1] + nextY) / 2;
4124
                                    }
4125
                                    resultPoint = new double[] { resultPoint[0], newY };
4126
                                }
4127
                            }
4128
                        }
4129
                        break;
4130
                    }
4131
                }
4132
            }
4133

    
4134
            x = resultPoint[0];
4135
            y = resultPoint[1];
4136

    
4137
            return targetConnector;
4138
        }
4139

    
4140
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4141
        {
4142
            LMConnector result = null;
4143
            List<LMConnector> connectors = new List<LMConnector>();
4144
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4145

    
4146
            if (modelItem != null)
4147
            {
4148
                foreach (LMRepresentation rep in modelItem.Representations)
4149
                {
4150
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4151
                        connectors.Add(dataSource.GetConnector(rep.Id));
4152
                }
4153

    
4154
                ReleaseCOMObjects(modelItem);
4155
            }
4156

    
4157
            if (connectors.Count == 1)
4158
                result = connectors[0];
4159
            else
4160
                foreach (var item in connectors)
4161
                    ReleaseCOMObjects(item);
4162

    
4163
            return result;
4164
        }
4165

    
4166
        private LMConnector GetLMConnectorFirst(string modelItemID)
4167
        {
4168
            LMConnector result = null;
4169
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4170

    
4171
            if (modelItem != null)
4172
            {
4173
                foreach (LMRepresentation rep in modelItem.Representations)
4174
                {
4175
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4176
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4177
                    {
4178
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4179
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4180
                        {
4181
                            result = connector;
4182
                            break;
4183
                        }
4184
                        else
4185
                        {
4186
                            ReleaseCOMObjects(connector);
4187
                            connector = null;
4188
                        }
4189
                    }
4190
                }
4191
                ReleaseCOMObjects(modelItem);
4192
                modelItem = null;
4193
            }
4194

    
4195
            return result;
4196
        }
4197

    
4198
        private int GetConnectorCount(string modelItemID)
4199
        {
4200
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4201
            int result = 0;
4202
            if (modelItem != null)
4203
            {
4204
                foreach (LMRepresentation rep in modelItem.Representations)
4205
                {
4206
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4207
                        result++;
4208
                    ReleaseCOMObjects(rep);
4209
                }
4210
                ReleaseCOMObjects(modelItem);
4211
            }
4212

    
4213
            return result;
4214
        }
4215

    
4216
        public List<string> GetRepresentations(string modelItemID)
4217
        {
4218
            List<string> result = new List<string>(); ;
4219
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4220
            if (modelItem != null)
4221
            {
4222
                foreach (LMRepresentation rep in modelItem.Representations)
4223
                {
4224
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4225
                        result.Add(rep.Id);
4226
                }
4227
                ReleaseCOMObjects(modelItem);
4228
            }
4229

    
4230
            return result;
4231
        }
4232

    
4233
        /// <summary>
4234
        /// Line Number Symbol을 실제로 Modeling하는 메서드
4235
        /// </summary>
4236
        /// <param name="lineNumber"></param>
4237
        private void LineNumberModelingOnlyOne(Line line)
4238
        {
4239
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
4240
            if (lineNumber != null)
4241
            {
4242
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4243
                if (connectedLMConnector != null)
4244
                {
4245
                    double x = 0;
4246
                    double y = 0;
4247
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4248

    
4249
                    Array points = new double[] { 0, x, y };
4250
                    lineNumber.SPPID.SPPID_X = x;
4251
                    lineNumber.SPPID.SPPID_Y = y;
4252
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4253

    
4254
                    if (_LmLabelPresist != null)
4255
                    {
4256
                        _LmLabelPresist.Commit();
4257
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4258
                        ReleaseCOMObjects(_LmLabelPresist);
4259
                    }
4260
                }
4261
            }
4262
        }
4263

    
4264
        private void LineNumberModeling(LineNumber lineNumber)
4265
        {
4266
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4267
            if (line != null)
4268
            {
4269
                double x = 0;
4270
                double y = 0;
4271
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4272

    
4273
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4274
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4275
                if (connectedLMConnector != null)
4276
                {
4277
                    Array points = new double[] { 0, x, y };
4278
                    lineNumber.SPPID.SPPID_X = x;
4279
                    lineNumber.SPPID.SPPID_Y = y;
4280
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4281

    
4282
                    if (_LmLabelPresist != null)
4283
                    {
4284
                        _LmLabelPresist.Commit();
4285
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4286
                        ReleaseCOMObjects(_LmLabelPresist);
4287
                    }
4288
                }
4289

    
4290
                foreach (var item in connectorVertices)
4291
                    ReleaseCOMObjects(item.Key);
4292
            }
4293
        }
4294
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4295
        {
4296
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4297
            if (line == null || line.SPPID.Vertices == null)
4298
                return;
4299

    
4300
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4301
            {
4302
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4303
                if (removeLabel != null)
4304
                {
4305
                    GridSetting gridSetting = GridSetting.GetInstance();
4306
                    double[] labelRange = null;
4307
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4308
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4309
                    List<double[]> vertices = GetConnectorVertices(connector);
4310

    
4311
                    double[] resultStart = null;
4312
                    double[] resultEnd = null;
4313
                    double distance = double.MaxValue;
4314
                    for (int i = 0; i < vertices.Count - 1; i++)
4315
                    {
4316
                        double[] startPoint = vertices[i];
4317
                        double[] endPoint = vertices[i + 1];
4318
                        foreach (var item in line.SPPID.Vertices)
4319
                        {
4320
                            double[] lineStartPoint = item[0];
4321
                            double[] lineEndPoint = item[item.Count - 1];
4322

    
4323
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4324
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4325
                            if (tempDistance < distance)
4326
                            {
4327
                                distance = tempDistance;
4328
                                resultStart = startPoint;
4329
                                resultEnd = endPoint;
4330
                            }
4331
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4332
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4333
                            if (tempDistance < distance)
4334
                            {
4335
                                distance = tempDistance;
4336
                                resultStart = startPoint;
4337
                                resultEnd = endPoint;
4338
                            }
4339
                        }
4340
                    }
4341

    
4342
                    if (resultStart != null && resultEnd != null)
4343
                    {
4344
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4345
                        double lineStartX = 0;
4346
                        double lineStartY = 0;
4347
                        double lineEndX = 0;
4348
                        double lineEndY = 0;
4349
                        double lineNumberX = 0;
4350
                        double lineNumberY = 0;
4351
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4352
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4353

    
4354
                        double lineX = (lineStartX + lineEndX) / 2;
4355
                        double lineY = (lineStartY + lineEndY) / 2;
4356
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4357
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4358

    
4359
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4360
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4361
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4362
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4363

    
4364
                        double offsetX = 0;
4365
                        double offsetY = 0;
4366
                        if (slope == SlopeType.HORIZONTAL)
4367
                        {
4368
                            // Line Number 아래
4369
                            if (lineY < lineNumberY)
4370
                            {
4371
                                offsetX = labelCenterX - SPPIDCenterX;
4372
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4373
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4374
                            }
4375
                            // Line Number 위
4376
                            else
4377
                            {
4378
                                offsetX = labelCenterX - SPPIDCenterX;
4379
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4380
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4381
                            }
4382
                        }
4383
                        else if (slope == SlopeType.VERTICAL)
4384
                        {
4385
                            // Line Number 오르쪽
4386
                            if (lineX < lineNumberX)
4387
                            {
4388
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4389
                                offsetY = labelCenterY - SPPIDCenterY;
4390
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4391
                            }
4392
                            // Line Number 왼쪽
4393
                            else
4394
                            {
4395
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4396
                                offsetY = labelCenterY - SPPIDCenterY;
4397
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4398
                            }
4399
                        }
4400

    
4401
                        if (offsetY != 0 && offsetY != 0)
4402
                        {
4403
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4404
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
4405
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
4406

    
4407
                            if (_LmLabelPresist != null)
4408
                            {
4409
                                _LmLabelPresist.Commit();
4410
                                lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4411
                            }
4412
                            ReleaseCOMObjects(_LmLabelPresist);
4413
                            _LmLabelPresist = null; 
4414
                        }
4415

    
4416
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4417
                        {
4418
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4419
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4420
                        }
4421
                    }
4422

    
4423

    
4424
                    ReleaseCOMObjects(connector);
4425
                    connector = null;
4426
                }
4427

    
4428
                ReleaseCOMObjects(removeLabel);
4429
                removeLabel = null;
4430
            }
4431
        }
4432
        /// <summary>
4433
        /// Flow Mark Modeling
4434
        /// </summary>
4435
        /// <param name="line"></param>
4436
        private void FlowMarkModeling(Line line)
4437
        {
4438
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4439
            {
4440
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4441
                if (connector != null)
4442
                {
4443
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4444
                    List<double[]> vertices = GetConnectorVertices(connector);
4445
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4446
                    double[] point = vertices[vertices.Count - 1];
4447
                    Array array = new double[] { 0, point[0], point[1] };
4448
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4449
                    if (_LMLabelPersist != null)
4450
                    {
4451
                        _LMLabelPersist.Commit();
4452
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4453
                        ReleaseCOMObjects(_LMLabelPersist);
4454
                    }
4455
                }
4456
            }
4457
        }
4458

    
4459
        /// <summary>
4460
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4461
        /// </summary>
4462
        /// <param name="lineNumber"></param>
4463
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4464
        {
4465
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4466
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4467
            {
4468
                if (a.ATTRIBUTE == "Tag Seq No")
4469
                    return 1;
4470
                else if (b.ATTRIBUTE == "Tag Seq No")
4471
                    return -1;
4472

    
4473
                return 0;
4474
            }
4475

    
4476
            foreach (LineRun run in lineNumber.RUNS)
4477
            {
4478
                foreach (var item in run.RUNITEMS)
4479
                {
4480
                    if (item.GetType() == typeof(Symbol))
4481
                    {
4482
                        Symbol symbol = item as Symbol;
4483
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4484
                        if (_LMSymbol != null)
4485
                        {
4486
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4487

    
4488
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4489
                            {
4490
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4491
                                {
4492
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4493
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4494
                                    {
4495
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4496
                                        if (_LMAAttribute != null)
4497
                                        {
4498
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4499
                                                _LMAAttribute.set_Value(attribute.VALUE);
4500
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4501
                                                _LMAAttribute.set_Value(attribute.VALUE);
4502
                                        }
4503
                                    }
4504
                                }
4505
                                _LMModelItem.Commit();
4506
                            }
4507
                            if (_LMModelItem != null)
4508
                                ReleaseCOMObjects(_LMModelItem);
4509
                        }
4510
                        if (_LMSymbol != null)
4511
                            ReleaseCOMObjects(_LMSymbol);
4512
                    }
4513
                    else if (item.GetType() == typeof(Line))
4514
                    {
4515
                        Line line = item as Line;
4516
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4517
                        {
4518
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4519
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4520
                            {
4521
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4522
                                {
4523
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4524
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4525
                                    {
4526
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4527
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
4528
                                        {
4529
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
4530
                                            if (_FluidSystemAttribute != null)
4531
                                            {
4532
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
4533
                                                if (dt.Rows.Count == 1)
4534
                                                {
4535
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
4536
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
4537
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4538
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
4539
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4540

    
4541
                                                    if (_LMAAttribute != null)
4542
                                                    {
4543
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4544
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4545
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4546
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4547
                                                    }
4548
                                                }
4549
                                                if (dt != null)
4550
                                                    dt.Dispose();
4551
                                            }
4552
                                        }
4553
                                        else if (_LMAAttribute != null)
4554
                                        {
4555
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4556
                                                _LMAAttribute.set_Value(attribute.VALUE);
4557
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4558
                                                _LMAAttribute.set_Value(attribute.VALUE);
4559
                                        }
4560
                                    }
4561
                                }
4562
                                _LMModelItem.Commit();
4563
                            }
4564
                            if (_LMModelItem != null)
4565
                                ReleaseCOMObjects(_LMModelItem);
4566
                            endLine.Add(line.SPPID.ModelItemId);
4567
                        }
4568
                    }
4569
                }
4570
            }
4571
        }
4572

    
4573
        /// <summary>
4574
        /// Symbol Attribute 입력 메서드
4575
        /// </summary>
4576
        /// <param name="item"></param>
4577
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4578
        {
4579
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4580
            string sRep = null;
4581
            if (targetItem.GetType() == typeof(Symbol))
4582
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4583
            else if (targetItem.GetType() == typeof(Equipment))
4584
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4585

    
4586
            if (!string.IsNullOrEmpty(sRep))
4587
            {
4588
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4589
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4590
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4591
                
4592
                foreach (var item in targetAttributes)
4593
                {
4594
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4595
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4596
                    {
4597
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4598
                        if (_Attribute != null)
4599
                        {
4600
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
4601
                            //if (associItem != null)
4602
                            //{
4603
                            //    if (associItem.GetType() == typeof(Text))
4604
                            //    {
4605
                            //        Text text = associItem as Text;
4606
                            //        text.SPPID.RepresentationId = "Attribute";
4607
                            //    }
4608
                            //    else if (associItem.GetType() == typeof(Note))
4609
                            //    {
4610
                            //        Note note = associItem as Note;
4611
                            //        note.SPPID.RepresentationId = "Attribute";
4612
                            //    }
4613
                            //}
4614
                            _Attribute.set_Value(item.VALUE);
4615
                            // OPC 일경우 Attribute 저장
4616
                            if (targetItem.GetType() == typeof(Symbol))
4617
                            {
4618
                                Symbol symbol = targetItem as Symbol;
4619
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4620
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4621
                            }
4622
                        }
4623
                    }
4624
                }
4625
                _LMModelItem.Commit();
4626

    
4627
                ReleaseCOMObjects(_Attributes);
4628
                ReleaseCOMObjects(_LMModelItem);
4629
                ReleaseCOMObjects(_LMSymbol);
4630
            }
4631
        }
4632

    
4633
        /// <summary>
4634
        /// Input SpecBreak Attribute
4635
        /// </summary>
4636
        /// <param name="specBreak"></param>
4637
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4638
        {
4639
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4640
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4641

    
4642
            if (upStreamObj != null &&
4643
                downStreamObj != null)
4644
            {
4645
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4646

    
4647
                if (targetLMConnector != null)
4648
                {
4649
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4650
                    {
4651
                        string symbolPath = _LMLabelPersist.get_FileName();
4652
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4653
                        if (mapping != null)
4654
                        {
4655
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4656
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4657
                            {
4658
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4659
                                if (values.Length == 2)
4660
                                {
4661
                                    string upStreamValue = values[0];
4662
                                    string downStreamValue = values[1];
4663

    
4664
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4665
                                }
4666
                            }
4667
                        }
4668
                    }
4669

    
4670
                    ReleaseCOMObjects(targetLMConnector);
4671
                }
4672
            }
4673

    
4674

    
4675
            #region 내부에서만 쓰는 메서드
4676
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4677
            {
4678
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4679
                Line upStreamLine = _upStreamObj as Line;
4680
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4681
                Line downStreamLine = _downStreamObj as Line;
4682
                // 둘다 Line일 경우
4683
                if (upStreamLine != null && downStreamLine != null)
4684
                {
4685
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4686
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4687
                }
4688
                // 둘다 Symbol일 경우
4689
                else if (upStreamSymbol != null && downStreamSymbol != null)
4690
                {
4691
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4692
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4693
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4694

    
4695
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4696
                    {
4697
                        if (connector.get_ItemStatus() != "Active")
4698
                            continue;
4699

    
4700
                        if (connector.Id != zeroLenthConnector.Id)
4701
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4702
                    }
4703

    
4704
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4705
                    {
4706
                        if (connector.get_ItemStatus() != "Active")
4707
                            continue;
4708

    
4709
                        if (connector.Id != zeroLenthConnector.Id)
4710
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4711
                    }
4712

    
4713
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4714
                    {
4715
                        if (connector.get_ItemStatus() != "Active")
4716
                            continue;
4717

    
4718
                        if (connector.Id != zeroLenthConnector.Id)
4719
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4720
                    }
4721

    
4722
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4723
                    {
4724
                        if (connector.get_ItemStatus() != "Active")
4725
                            continue;
4726

    
4727
                        if (connector.Id != zeroLenthConnector.Id)
4728
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4729
                    }
4730

    
4731
                    ReleaseCOMObjects(zeroLenthConnector);
4732
                    ReleaseCOMObjects(upStreamLMSymbol);
4733
                    ReleaseCOMObjects(downStreamLMSymbol);
4734
                }
4735
                else if (upStreamSymbol != null && downStreamLine != null)
4736
                {
4737
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4738
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4739
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4740

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

    
4746
                        if (connector.Id == zeroLenthConnector.Id)
4747
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4748
                    }
4749

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

    
4755
                        if (connector.Id == zeroLenthConnector.Id)
4756
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4757
                    }
4758

    
4759
                    ReleaseCOMObjects(zeroLenthConnector);
4760
                    ReleaseCOMObjects(upStreamLMSymbol);
4761
                }
4762
                else if (upStreamLine != null && downStreamSymbol != null)
4763
                {
4764
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4765
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4766
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4767

    
4768
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4769
                    {
4770
                        if (connector.get_ItemStatus() != "Active")
4771
                            continue;
4772

    
4773
                        if (connector.Id == zeroLenthConnector.Id)
4774
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4775
                    }
4776

    
4777
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4778
                    {
4779
                        if (connector.get_ItemStatus() != "Active")
4780
                            continue;
4781

    
4782
                        if (connector.Id == zeroLenthConnector.Id)
4783
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4784
                    }
4785

    
4786
                    ReleaseCOMObjects(zeroLenthConnector);
4787
                    ReleaseCOMObjects(downStreamLMSymbol);
4788
                }
4789
            }
4790

    
4791
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4792
            {
4793
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4794
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4795
                {
4796
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4797
                    if (_LMAAttribute != null)
4798
                    {
4799
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4800
                            _LMAAttribute.set_Value(value);
4801
                        else if (_LMAAttribute.get_Value() != value)
4802
                            _LMAAttribute.set_Value(value);
4803
                    }
4804

    
4805
                    _LMModelItem.Commit();
4806
                }
4807
                if (_LMModelItem != null)
4808
                    ReleaseCOMObjects(_LMModelItem);
4809
            }
4810

    
4811
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4812
            {
4813
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4814
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4815
                {
4816
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4817
                    if (_LMAAttribute != null)
4818
                    {
4819
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4820
                            _LMAAttribute.set_Value(value);
4821
                        else if (_LMAAttribute.get_Value() != value)
4822
                            _LMAAttribute.set_Value(value);
4823
                    }
4824

    
4825
                    _LMModelItem.Commit();
4826
                }
4827
                if (_LMModelItem != null)
4828
                    ReleaseCOMObjects(_LMModelItem);
4829
            }
4830
            #endregion
4831
        }
4832

    
4833
        private void InputEndBreakAttribute(EndBreak endBreak)
4834
        {
4835
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4836
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4837

    
4838
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4839
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4840
            {
4841
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4842
                if (labelPersist != null)
4843
                {
4844
                    LMRepresentation representation = labelPersist.RepresentationObject;
4845
                    if (representation != null)
4846
                    {
4847
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4848
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4849
                        string modelItemID = connector.ModelItemID;
4850
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4851
                        {
4852
                            List<string> modelItemIDs = new List<string>();
4853
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4854
                            {
4855
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4856
                                foreach (LMConnector item in symbol.Connect1Connectors)
4857
                                {
4858
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4859
                                        modelItemIDs.Add(item.ModelItemID);
4860
                                    ReleaseCOMObjects(item);
4861
                                }
4862
                                foreach (LMConnector item in symbol.Connect2Connectors)
4863
                                {
4864
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4865
                                        modelItemIDs.Add(item.ModelItemID);
4866
                                    ReleaseCOMObjects(item);
4867
                                }
4868
                                ReleaseCOMObjects(symbol);
4869
                                symbol = null;
4870
                            }
4871
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4872
                            {
4873
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4874
                                foreach (LMConnector item in symbol.Connect1Connectors)
4875
                                {
4876
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4877
                                        modelItemIDs.Add(item.ModelItemID);
4878
                                    ReleaseCOMObjects(item);
4879
                                }
4880
                                foreach (LMConnector item in symbol.Connect2Connectors)
4881
                                {
4882
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4883
                                        modelItemIDs.Add(item.ModelItemID);
4884
                                    ReleaseCOMObjects(item);
4885
                                }
4886
                                ReleaseCOMObjects(symbol);
4887
                                symbol = null;
4888
                            }
4889

    
4890
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4891
                            if (modelItemIDs.Count == 1)
4892
                            {
4893
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4894
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4895
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4896
                                {
4897
                                    bool result = false;
4898
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4899
                                    {
4900
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4901
                                            result = true;
4902
                                        ReleaseCOMObjects(loop);
4903
                                    }
4904

    
4905
                                    if (result)
4906
                                    {
4907
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4908
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4909
                                        ZeroLengthModelItem.Commit();
4910
                                    }
4911
                                    else
4912
                                    {
4913
                                        List<string> loopModelItems = new List<string>();
4914
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4915
                                        {
4916
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4917
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4918
                                            {
4919
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4920
                                                    loopModelItems.Add(loop.ModelItemID);
4921
                                                ReleaseCOMObjects(loop);
4922
                                            }
4923
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4924
                                            {
4925
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4926
                                                    loopModelItems.Add(loop.ModelItemID);
4927
                                                ReleaseCOMObjects(loop);
4928
                                            }
4929
                                            ReleaseCOMObjects(_symbol);
4930
                                            _symbol = null;
4931
                                        }
4932
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4933
                                        {
4934
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4935
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4936
                                            {
4937
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4938
                                                    loopModelItems.Add(loop.ModelItemID);
4939
                                                ReleaseCOMObjects(loop);
4940
                                            }
4941
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4942
                                            {
4943
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4944
                                                    loopModelItems.Add(loop.ModelItemID);
4945
                                                ReleaseCOMObjects(loop);
4946
                                            }
4947
                                            ReleaseCOMObjects(_symbol);
4948
                                            _symbol = null;
4949
                                        }
4950

    
4951
                                        loopModelItems = loopModelItems.Distinct().ToList();
4952
                                        if (loopModelItems.Count == 1)
4953
                                        {
4954
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4955
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
4956
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
4957
                                            modelItem.Commit();
4958
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4959
                                            ZeroLengthModelItem.Commit();
4960

    
4961
                                            ReleaseCOMObjects(loopModelItem);
4962
                                            loopModelItem = null;
4963
                                        }
4964
                                    }
4965
                                }
4966
                                else
4967
                                {
4968
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4969
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4970
                                    ZeroLengthModelItem.Commit();
4971
                                }
4972
                                ReleaseCOMObjects(modelItem);
4973
                                modelItem = null;
4974
                                ReleaseCOMObjects(onlyOne);
4975
                                onlyOne = null;
4976
                            }
4977
                        }
4978
                        ReleaseCOMObjects(connector);
4979
                        connector = null;
4980
                        ReleaseCOMObjects(ZeroLengthModelItem);
4981
                        ZeroLengthModelItem = null;
4982
                    }
4983
                    ReleaseCOMObjects(representation);
4984
                    representation = null;
4985
                }
4986
                ReleaseCOMObjects(labelPersist);
4987
                labelPersist = null;
4988
            }
4989
        }
4990

    
4991
        /// <summary>
4992
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4993
        /// </summary>
4994
        /// <param name="text"></param>
4995
        private void NormalTextModeling(Text text)
4996
        {
4997
            LMSymbol _LMSymbol = null;
4998

    
4999
            LMItemNote _LMItemNote = null;
5000
            LMAAttribute _LMAAttribute = null;
5001

    
5002
            double x = 0;
5003
            double y = 0;
5004
            double angle = text.ANGLE;
5005
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5006

    
5007
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5008
            text.SPPID.SPPID_X = x;
5009
            text.SPPID.SPPID_Y = y;
5010

    
5011
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5012
            if (_LMSymbol != null)
5013
            {
5014
                _LMSymbol.Commit();
5015
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5016
                if (_LMItemNote != null)
5017
                {
5018
                    _LMItemNote.Commit();
5019
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5020
                    if (_LMAAttribute != null)
5021
                    {
5022
                        _LMAAttribute.set_Value(text.VALUE);
5023
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5024
                        _LMItemNote.Commit();
5025

    
5026

    
5027
                        double[] range = null;
5028
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5029
                        {
5030
                            double[] temp = null;
5031
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5032
                            if (temp != null)
5033
                            {
5034
                                if (range == null)
5035
                                    range = temp;
5036
                                else
5037
                                {
5038
                                    range = new double[] {
5039
                                            Math.Min(range[0], temp[0]),
5040
                                            Math.Min(range[1], temp[1]),
5041
                                            Math.Max(range[2], temp[2]),
5042
                                            Math.Max(range[3], temp[3])
5043
                                        };
5044
                                }
5045
                            }
5046
                        }
5047
                        text.SPPID.Range = range;
5048

    
5049
                        if (_LMAAttribute != null)
5050
                            ReleaseCOMObjects(_LMAAttribute);
5051
                        if (_LMItemNote != null)
5052
                            ReleaseCOMObjects(_LMItemNote);
5053
                    }
5054

    
5055
                    TextCorrectModeling(text);
5056
                }
5057
            }
5058
            if (_LMSymbol != null)
5059
                ReleaseCOMObjects(_LMSymbol);
5060
        }
5061

    
5062
        private void AssociationTextModeling(Text text)
5063
        {
5064
            LMSymbol _LMSymbol = null;
5065
            LMConnector connectedLMConnector = null;
5066
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5067
            if (owner != null && owner.GetType() == typeof(Symbol))
5068
            {
5069
                Symbol symbol = owner as Symbol;
5070
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5071
                if (_LMSymbol != null)
5072
                {
5073
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5074
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5075
                    {
5076
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5077

    
5078
                        if (mapping != null)
5079
                        {
5080
                            double x = 0;
5081
                            double y = 0;
5082

    
5083
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5084
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5085
                            Array array = new double[] { 0, x, y };
5086
                            text.SPPID.SPPID_X = x;
5087
                            text.SPPID.SPPID_Y = y;
5088
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5089
                            if (_LMLabelPersist != null)
5090
                            {
5091
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5092
                                _LMLabelPersist.Commit();
5093
                                ReleaseCOMObjects(_LMLabelPersist);
5094
                            }
5095
                        }
5096
                    }
5097
                }
5098
            }
5099
            else if (owner != null && owner.GetType() == typeof(Line))
5100
            {
5101
                Line line = owner as Line;
5102
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5103
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5104

    
5105
                if (connectedLMConnector != null)
5106
                {
5107
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5108
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5109
                    {
5110
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5111

    
5112
                        if (mapping != null)
5113
                        {
5114
                            double x = 0;
5115
                            double y = 0;
5116
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5117
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5118
                            Array array = new double[] { 0, x, y };
5119

    
5120
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5121
                            if (_LMLabelPersist != null)
5122
                            {
5123
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5124
                                _LMLabelPersist.Commit();
5125
                                ReleaseCOMObjects(_LMLabelPersist);
5126
                            }
5127
                        }
5128
                    }
5129
                }
5130
            }
5131
            if (_LMSymbol != null)
5132
                ReleaseCOMObjects(_LMSymbol);
5133
        }
5134

    
5135
        private void TextCorrectModeling(Text text)
5136
        {
5137
            if (text.SPPID.Range == null)
5138
                return;
5139

    
5140
            bool needRemodeling = false;
5141
            bool loop = true;
5142
            GridSetting gridSetting = GridSetting.GetInstance();
5143
            while (loop)
5144
            {
5145
                loop = false;
5146
                foreach (var overlapText in document.TEXTINFOS)
5147
                {
5148
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5149
                        continue;
5150

    
5151
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5152
                    {
5153
                        double percentX = 0;
5154
                        double percentY = 0;
5155
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5156
                        {
5157
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5158
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5159
                        }
5160
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5161
                        {
5162
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5163
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5164
                        }
5165

    
5166
                        double tempX = 0;
5167
                        double tempY = 0;
5168
                        bool overlapX = false;
5169
                        bool overlapY = false;
5170
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5171
                        if (percentX >= percentY)
5172
                        {
5173
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5174
                            double move = gridSetting.Length * count;
5175
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5176
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5177
                            needRemodeling = true;
5178
                            loop = true;
5179
                        }
5180
                        else
5181
                        {
5182
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5183
                            double move = gridSetting.Length * count;
5184
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5185
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5186
                            needRemodeling = true;
5187
                            loop = true;
5188
                        }
5189
                    }
5190
                }
5191
            }
5192
            
5193

    
5194
            if (needRemodeling)
5195
            {
5196
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5197
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5198
                text.SPPID.RepresentationId = null;
5199

    
5200
                LMItemNote _LMItemNote = null;
5201
                LMAAttribute _LMAAttribute = null;
5202
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5203
                if (_LMSymbol != null)
5204
                {
5205
                    _LMSymbol.Commit();
5206
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5207
                    if (_LMItemNote != null)
5208
                    {
5209
                        _LMItemNote.Commit();
5210
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5211
                        if (_LMAAttribute != null)
5212
                        {
5213
                            _LMAAttribute.set_Value(text.VALUE);
5214
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5215
                            _LMItemNote.Commit();
5216

    
5217
                            ReleaseCOMObjects(_LMAAttribute);
5218
                            ReleaseCOMObjects(_LMItemNote);
5219
                        }
5220
                    }
5221
                }
5222

    
5223
                ReleaseCOMObjects(symbol);
5224
                symbol = null;
5225
                ReleaseCOMObjects(_LMItemNote);
5226
                _LMItemNote = null;
5227
                ReleaseCOMObjects(_LMAAttribute);
5228
                _LMAAttribute = null;
5229
                ReleaseCOMObjects(_LMSymbol);
5230
                _LMSymbol = null;
5231
            }
5232
        }
5233

    
5234
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5235
        {
5236
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5237
            {
5238
                List<Text> texts = new List<Text>();
5239
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5240
                LMRepresentation representation = targetLabel.RepresentationObject;
5241
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5242
                if (targetLabel.RepresentationObject != null && symbol != null)
5243
                {
5244
                    double[] symbolRange = null;
5245
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5246
                    if (symbolRange != null)
5247
                    {
5248
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5249
                        {
5250
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5251
                            if (findText != null)
5252
                            {
5253
                                double[] range = null;
5254
                                GetSPPIDSymbolRange(labelPersist, ref range);
5255
                                findText.SPPID.Range = range;
5256
                                texts.Add(findText);
5257
                            }
5258

    
5259
                            ReleaseCOMObjects(labelPersist);
5260
                        }
5261

    
5262
                        if (texts.Count > 0)
5263
                        {
5264
                            #region Sort Text By Y
5265
                            texts.Sort(SortTextByY);
5266
                            int SortTextByY(Text a, Text b)
5267
                            {
5268
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5269
                            }
5270
                            #endregion
5271

    
5272
                            #region 첫번째 Text로 기준 맞춤
5273
                            for (int i = 0; i < texts.Count; i++)
5274
                            {
5275
                                if (i != 0)
5276
                                {
5277
                                    Text currentText = texts[i];
5278
                                    Text prevText = texts[i - 1];
5279
                                    double minY = prevText.SPPID.Range[1];
5280
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5281
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5282
                                    double _gapX = centerX - centerPrevX;
5283
                                    double _gapY = currentText.SPPID.Range[3] - minY;
5284
                                    MoveText(currentText, _gapX, _gapY);
5285
                                }
5286
                            }
5287
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5288
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5289
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5290
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5291
                            rangeMinX.Sort();
5292
                            rangeMinY.Sort();
5293
                            rangeMaxX.Sort();
5294
                            rangeMaxY.Sort();
5295
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5296
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5297
                            #endregion
5298

    
5299
                            Text correctBySymbol = texts[0];
5300
                            double textCenterX = (text.X1 + text.X2) / 2;
5301
                            double textCenterY = (text.Y1 + text.Y2) / 2;
5302
                            double originX = 0;
5303
                            double originY = 0;
5304
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5305
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5306
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5307
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5308

    
5309
                            double gapX = 0;
5310
                            double gapY = 0;
5311
                            if (angle < 45)
5312
                            {
5313
                                // Text 오른쪽
5314
                                if (textCenterX > originX)
5315
                                {
5316
                                    gapX = rangeMinX[0] - symbolRange[2];
5317
                                    gapY = allTextCenterY - symbolCenterY;
5318
                                }
5319
                                // Text 왼쪽
5320
                                else
5321
                                {
5322
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5323
                                    gapY = allTextCenterY - symbolCenterY;
5324
                                }
5325
                            }
5326
                            else
5327
                            {
5328
                                // Text 아래쪽
5329
                                if (textCenterY > originY)
5330
                                {
5331
                                    gapX = allTextCenterX - symbolCenterX;
5332
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5333
                                }
5334
                                // Text 위쪽
5335
                                else
5336
                                {
5337
                                    gapX = allTextCenterX - symbolCenterX;
5338
                                    gapY = rangeMinY[0] - symbolRange[3];
5339
                                }
5340
                            }
5341

    
5342
                            foreach (var item in texts)
5343
                            {
5344
                                MoveText(item, gapX, gapY);
5345
                                RemodelingAssociationText(item);
5346
                            }
5347
                        }
5348
                    }
5349
                }
5350

    
5351
                void MoveText(Text moveText, double x, double y)
5352
                {
5353
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5354
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5355
                    moveText.SPPID.Range = new double[] {
5356
                        moveText.SPPID.Range[0] - x,
5357
                        moveText.SPPID.Range[1]- y,
5358
                        moveText.SPPID.Range[2]- x,
5359
                        moveText.SPPID.Range[3]- y
5360
                    };
5361
                }
5362

    
5363
                endTexts.AddRange(texts);
5364

    
5365
                ReleaseCOMObjects(targetLabel);
5366
                targetLabel = null;
5367
                ReleaseCOMObjects(representation);
5368
                representation = null;
5369
            }
5370
        }
5371

    
5372
        private void RemodelingAssociationText(Text text)
5373
        {
5374
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5375
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5376
            removeLabel.Commit();
5377
            ReleaseCOMObjects(removeLabel);
5378
            removeLabel = null;
5379

    
5380
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5381
            if (owner != null && owner.GetType() == typeof(Symbol))
5382
            {
5383
                Symbol symbol = owner as Symbol;
5384
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5385
                if (_LMSymbol != null)
5386
                {
5387
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5388
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5389
                    {
5390
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5391

    
5392
                        if (mapping != null)
5393
                        {
5394
                            double x = 0;
5395
                            double y = 0;
5396

    
5397
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5398
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5399
                            if (_LMLabelPersist != null)
5400
                            {
5401
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5402
                                _LMLabelPersist.Commit();
5403
                            }
5404
                            ReleaseCOMObjects(_LMLabelPersist);
5405
                            _LMLabelPersist = null;
5406
                        }
5407
                    }
5408
                }
5409
                ReleaseCOMObjects(_LMSymbol);
5410
                _LMSymbol = null;
5411
            }
5412
        }
5413

    
5414
        /// <summary>
5415
        /// Note Modeling
5416
        /// </summary>
5417
        /// <param name="note"></param>
5418
        private void NoteModeling(Note note, List<Note> correctList)
5419
        {
5420
            LMSymbol _LMSymbol = null;
5421
            LMItemNote _LMItemNote = null;
5422
            LMAAttribute _LMAAttribute = null;
5423

    
5424
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5425
            {
5426
                double x = 0;
5427
                double y = 0;
5428

    
5429
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5430
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5431
                note.SPPID.SPPID_X = x;
5432
                note.SPPID.SPPID_Y = y;
5433

    
5434
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5435
                if (_LMSymbol != null)
5436
                {
5437
                    _LMSymbol.Commit();
5438
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5439
                    if (_LMItemNote != null)
5440
                    {
5441
                        _LMItemNote.Commit();
5442
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5443
                        if (_LMAAttribute != null)
5444
                        {
5445
                            _LMAAttribute.set_Value(note.VALUE);
5446
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5447

    
5448
                            double[] range = null;
5449
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5450
                            {
5451
                                double[] temp = null;
5452
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5453
                                if (temp != null)
5454
                                {
5455
                                    if (range == null)
5456
                                        range = temp;
5457
                                    else
5458
                                    {
5459
                                        range = new double[] {
5460
                                            Math.Min(range[0], temp[0]),
5461
                                            Math.Min(range[1], temp[1]),
5462
                                            Math.Max(range[2], temp[2]),
5463
                                            Math.Max(range[3], temp[3])
5464
                                        };
5465
                                    }
5466
                                }
5467
                            }
5468
                            if (range != null)
5469
                                correctList.Add(note);
5470
                            note.SPPID.Range = range;
5471

    
5472

    
5473
                            _LMItemNote.Commit();
5474
                        }
5475
                    }
5476
                }
5477
            }
5478

    
5479
            if (_LMAAttribute != null)
5480
                ReleaseCOMObjects(_LMAAttribute);
5481
            if (_LMItemNote != null)
5482
                ReleaseCOMObjects(_LMItemNote);
5483
            if (_LMSymbol != null)
5484
                ReleaseCOMObjects(_LMSymbol);
5485
        }
5486

    
5487
        private void NoteCorrectModeling(Note note, List<Note> endList)
5488
        {
5489
            bool needRemodeling = false;
5490
            bool loop = true;
5491
            GridSetting gridSetting = GridSetting.GetInstance();
5492
            while (loop)
5493
            {
5494
                loop = false;
5495
                foreach (var overlap in endList)
5496
                {
5497
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5498
                    {
5499
                        double tempX = 0;
5500
                        double tempY = 0;
5501
                        bool overlapX = false;
5502
                        bool overlapY = false;
5503
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5504
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5505
                        if (overlapY && angle >= 45)
5506
                        {
5507
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5508
                            double move = gridSetting.Length * count;
5509
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5510
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5511
                            needRemodeling = true;
5512
                            loop = true;
5513
                        }
5514
                        if (overlapX && angle <= 45)
5515
                        {
5516
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5517
                            double move = gridSetting.Length * count;
5518
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5519
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5520
                            needRemodeling = true;
5521
                            loop = true;
5522
                        }
5523
                    }
5524
                }
5525
            }
5526

    
5527

    
5528
            if (needRemodeling)
5529
            {
5530
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5531
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5532
                note.SPPID.RepresentationId = null;
5533

    
5534
                LMItemNote _LMItemNote = null;
5535
                LMAAttribute _LMAAttribute = null;
5536
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5537
                if (_LMSymbol != null)
5538
                {
5539
                    _LMSymbol.Commit();
5540
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5541
                    if (_LMItemNote != null)
5542
                    {
5543
                        _LMItemNote.Commit();
5544
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5545
                        if (_LMAAttribute != null)
5546
                        {
5547
                            _LMAAttribute.set_Value(note.VALUE);
5548
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5549
                            _LMItemNote.Commit();
5550

    
5551
                            ReleaseCOMObjects(_LMAAttribute);
5552
                            ReleaseCOMObjects(_LMItemNote);
5553
                        }
5554
                    }
5555
                }
5556

    
5557
                ReleaseCOMObjects(symbol);
5558
                symbol = null;
5559
                ReleaseCOMObjects(_LMItemNote);
5560
                _LMItemNote = null;
5561
                ReleaseCOMObjects(_LMAAttribute);
5562
                _LMAAttribute = null;
5563
                ReleaseCOMObjects(_LMSymbol);
5564
                _LMSymbol = null;
5565
            }
5566

    
5567
            endList.Add(note);
5568
        }
5569

    
5570
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5571
        {
5572
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5573
            if (modelItem != null)
5574
            {
5575
                foreach (LMRepresentation rep in modelItem.Representations)
5576
                {
5577
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5578
                    {
5579
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5580
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5581
                        {
5582
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5583
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5584
                            if (modelItemIds.Count == 1)
5585
                            {
5586
                                string joinModelItemId = modelItemIds[0];
5587
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5588
                                if (survivorId != null)
5589
                                    break;
5590
                            }
5591
                        }
5592
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5593
                        {
5594
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5595
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5596
                            if (modelItemIds.Count == 1)
5597
                            {
5598
                                string joinModelItemId = modelItemIds[0];
5599
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5600
                                if (survivorId != null)
5601
                                    break;
5602
                            }
5603
                        }
5604
                    }
5605
                }
5606
            }
5607
        }
5608

    
5609
        /// <summary>
5610
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5611
        /// </summary>
5612
        /// <param name="x"></param>
5613
        /// <param name="y"></param>
5614
        /// <param name="originX"></param>
5615
        /// <param name="originY"></param>
5616
        /// <param name="SPPIDLabelLocation"></param>
5617
        /// <param name="location"></param>
5618
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5619
        {
5620
            if (location == Location.None)
5621
            {
5622
                x = originX;
5623
                y = originY;
5624
            }
5625
            else
5626
            {
5627
                if (location.HasFlag(Location.Center))
5628
                {
5629
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5630
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5631
                }
5632

    
5633
                if (location.HasFlag(Location.Left))
5634
                    x = SPPIDLabelLocation.X1;
5635
                else if (location.HasFlag(Location.Right))
5636
                    x = SPPIDLabelLocation.X2;
5637

    
5638
                if (location.HasFlag(Location.Down))
5639
                    y = SPPIDLabelLocation.Y1;
5640
                else if (location.HasFlag(Location.Up))
5641
                    y = SPPIDLabelLocation.Y2;
5642
            }
5643
        }
5644

    
5645
        /// <summary>
5646
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5647
        /// 1. Angle Valve
5648
        /// 2. 3개로 이루어진 Symbol Group
5649
        /// </summary>
5650
        /// <returns></returns>
5651
        private List<Symbol> GetPrioritySymbol()
5652
        {
5653
            DataTable symbolTable = document.SymbolTable;
5654
            // List에 순서대로 쌓는다.
5655
            List<Symbol> symbols = new List<Symbol>();
5656

    
5657
            // Angle Valve 부터
5658
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5659
            {
5660
                if (!symbols.Contains(symbol))
5661
                {
5662
                    double originX = 0;
5663
                    double originY = 0;
5664

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

    
5669
                    SlopeType slopeType1 = SlopeType.None;
5670
                    SlopeType slopeType2 = SlopeType.None;
5671
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5672
                    {
5673
                        double connectorX = 0;
5674
                        double connectorY = 0;
5675
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5676
                        if (slopeType1 == SlopeType.None)
5677
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5678
                        else
5679
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5680
                    }
5681

    
5682
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5683
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5684
                        symbols.Add(symbol);
5685
                }
5686
            }
5687

    
5688
            List<Symbol> tempSymbols = new List<Symbol>();
5689
            // Conn 갯수 기준
5690
            foreach (var item in document.SYMBOLS)
5691
            {
5692
                if (!symbols.Contains(item))
5693
                    tempSymbols.Add(item);
5694
            }
5695
            tempSymbols.Sort(SortSymbolPriority);
5696
            symbols.AddRange(tempSymbols);
5697

    
5698
            return symbols;
5699
        }
5700

    
5701
        private void SetPriorityLine(List<Line> lines)
5702
        {
5703
            lines.Sort(SortLinePriority);
5704

    
5705
            int SortLinePriority(Line a, Line b)
5706
            {
5707
                // Branch 없는것부터
5708
                int branchRetval = CompareBranchLine(a, b);
5709
                if (branchRetval != 0)
5710
                {
5711
                    return branchRetval;
5712
                }
5713
                else
5714
                {
5715
                    // Symbol 연결 갯수
5716
                    int connSymbolRetval = CompareConnSymbol(a, b);
5717
                    if (connSymbolRetval != 0)
5718
                    {
5719
                        return connSymbolRetval;
5720
                    }
5721
                    else
5722
                    {
5723
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5724
                        int connItemRetval = CompareConnItem(a, b);
5725
                        if (connItemRetval != 0)
5726
                        {
5727
                            return connItemRetval;
5728
                        }
5729
                        else
5730
                        {
5731
                            // ConnectedItem이 없는것
5732
                            int noneConnRetval = CompareNoneConn(a, b);
5733
                            if (noneConnRetval != 0)
5734
                            {
5735
                                return noneConnRetval;
5736
                            }
5737
                            else
5738
                            {
5739

    
5740
                            }
5741
                        }
5742
                    }
5743
                }
5744

    
5745
                return 0;
5746
            }
5747

    
5748
            int CompareNotSegmentLine(Line a, Line b)
5749
            {
5750
                List<Connector> connectorsA = a.CONNECTORS
5751
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5752
                    .ToList();
5753

    
5754
                List<Connector> connectorsB = b.CONNECTORS
5755
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5756
                    .ToList();
5757

    
5758
                // 오름차순
5759
                return connectorsB.Count.CompareTo(connectorsA.Count);
5760
            }
5761

    
5762
            int CompareConnSymbol(Line a, Line b)
5763
            {
5764
                List<Connector> connectorsA = a.CONNECTORS
5765
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5766
                    .ToList();
5767

    
5768
                List<Connector> connectorsB = b.CONNECTORS
5769
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5770
                    .ToList();
5771

    
5772
                // 오름차순
5773
                return connectorsB.Count.CompareTo(connectorsA.Count);
5774
            }
5775

    
5776
            int CompareConnItem(Line a, Line b)
5777
            {
5778
                List<Connector> connectorsA = a.CONNECTORS
5779
                    .Where(conn => conn.ConnectedObject != null && 
5780
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5781
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5782
                    .ToList();
5783

    
5784
                List<Connector> connectorsB = b.CONNECTORS
5785
                    .Where(conn => conn.ConnectedObject != null &&
5786
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5787
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5788
                    .ToList();
5789

    
5790
                // 오름차순
5791
                return connectorsB.Count.CompareTo(connectorsA.Count);
5792
            }
5793

    
5794
            int CompareBranchLine(Line a, Line b)
5795
            {
5796
                List<Connector> connectorsA = a.CONNECTORS
5797
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5798
                    .ToList();
5799
                List<Connector> connectorsB = b.CONNECTORS
5800
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5801
                    .ToList();
5802

    
5803
                // 내림차순
5804
                return connectorsA.Count.CompareTo(connectorsB.Count);
5805
            }
5806

    
5807
            int CompareNoneConn(Line a, Line b)
5808
            {
5809
                List<Connector> connectorsA = a.CONNECTORS
5810
                    .Where(conn => conn.ConnectedObject == null)
5811
                    .ToList();
5812

    
5813
                List<Connector> connectorsB = b.CONNECTORS
5814
                    .Where(conn => conn.ConnectedObject == null)
5815
                    .ToList();
5816

    
5817
                // 오름차순
5818
                return connectorsB.Count.CompareTo(connectorsA.Count);
5819
            }
5820
        }
5821

    
5822
        private void SortText(List<Text> texts)
5823
        {
5824
            texts.Sort(Sort);
5825

    
5826
            int Sort(Text a, Text b)
5827
            {
5828
                int yRetval = CompareY(a, b);
5829
                if (yRetval != 0)
5830
                {
5831
                    return yRetval;
5832
                }
5833
                else
5834
                {
5835
                    return CompareX(a, b);
5836
                }
5837
            }
5838

    
5839
            int CompareY(Text a, Text b)
5840
            {
5841
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5842
            }
5843

    
5844
            int CompareX(Text a, Text b)
5845
            {
5846
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5847
            }
5848
        }
5849
        private void SortNote(List<Note> notes)
5850
        {
5851
            notes.Sort(Sort);
5852

    
5853
            int Sort(Note a, Note b)
5854
            {
5855
                int yRetval = CompareY(a, b);
5856
                if (yRetval != 0)
5857
                {
5858
                    return yRetval;
5859
                }
5860
                else
5861
                {
5862
                    return CompareX(a, b);
5863
                }
5864
            }
5865

    
5866
            int CompareY(Note a, Note b)
5867
            {
5868
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5869
            }
5870

    
5871
            int CompareX(Note a, Note b)
5872
            {
5873
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5874
            }
5875
        }
5876

    
5877
        private void SortBranchLines()
5878
        {
5879
            BranchLines.Sort(SortBranchLine);
5880
            int SortBranchLine(Line a, Line b)
5881
            {
5882
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5883
                 x.ConnectedObject.GetType() == typeof(Line) &&
5884
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5885
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5886

    
5887
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5888
                 x.ConnectedObject.GetType() == typeof(Line) &&
5889
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5890
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5891

    
5892
                // 내림차순
5893
                return countA.CompareTo(countB);
5894
            }
5895
        }
5896

    
5897
        private static int SortSymbolPriority(Symbol a, Symbol b)
5898
        {
5899
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5900
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5901
            int retval = countB.CompareTo(countA);
5902
            if (retval != 0)
5903
                return retval;
5904
            else
5905
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5906
        }
5907

    
5908
        private string GetSPPIDFileName(LMModelItem modelItem)
5909
        {
5910
            string symbolPath = null;
5911
            foreach (LMRepresentation rep in modelItem.Representations)
5912
            {
5913
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5914
                {
5915
                    symbolPath = rep.get_FileName();
5916
                    break;
5917
                }
5918
            }
5919
            return symbolPath;
5920
        }
5921

    
5922
        private string GetSPPIDFileName(string modelItemId)
5923
        {
5924
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5925
            string symbolPath = null;
5926
            foreach (LMRepresentation rep in modelItem.Representations)
5927
            {
5928
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5929
                {
5930
                    symbolPath = rep.get_FileName();
5931
                    break;
5932
                }
5933
            }
5934
            ReleaseCOMObjects(modelItem);
5935
            return symbolPath;
5936
        }
5937

    
5938
        /// <summary>
5939
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5940
        /// </summary>
5941
        /// <param name="graphicOID"></param>
5942
        /// <param name="milliseconds"></param>
5943
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5944
        {
5945
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5946
            {
5947
                double minX = 0;
5948
                double minY = 0;
5949
                double maxX = 0;
5950
                double maxY = 0;
5951
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5952
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5953

    
5954
                Thread.Sleep(milliseconds);
5955
            }
5956
        }
5957

    
5958
        /// <summary>
5959
        /// ComObject를 Release
5960
        /// </summary>
5961
        /// <param name="objVars"></param>
5962
        public void ReleaseCOMObjects(params object[] objVars)
5963
        {
5964
            if (objVars != null)
5965
            {
5966
                int intNewRefCount = 0;
5967
                foreach (object obj in objVars)
5968
                {
5969
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5970
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5971
                }
5972
            }
5973
        }
5974

    
5975
        /// IDisposable 구현
5976
        ~AutoModeling()
5977
        {
5978
            this.Dispose(false);
5979
        }
5980

    
5981
        private bool disposed;
5982
        public void Dispose()
5983
        {
5984
            this.Dispose(true);
5985
            GC.SuppressFinalize(this);
5986
        }
5987

    
5988
        protected virtual void Dispose(bool disposing)
5989
        {
5990
            if (this.disposed) return;
5991
            if (disposing)
5992
            {
5993
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5994
            }
5995
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5996
            this.disposed = true;
5997
        }
5998
    }
5999
}
클립보드 이미지 추가 (최대 크기: 500 MB)