프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ d2cffa33

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

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

    
50
        List<double[]> itemRange = new List<double[]>();
51

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

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

    
65
            this.closeDocument = closeDocument;
66
            this.document = document;
67
            this._ETCSetting = ETCSetting.GetInstance();
68
        }
69

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

    
82
                }
83
            }
84
        }
85

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

    
107
                    // VendorPackage Modeling
108
                    // ID2에서 VendorPackage로 된 Symbol을 SPPID에서 그림
109
                    RunVendorPackageModeling();
110
                    // Equipment Modeling
111
                    // Id2에서 인식한 Equipment일 경우 SPPID에 Draft
112
                    RunEquipmentModeling();
113
                    // Symbol Modeling
114
                    // ID2의 Symbol Draft
115
                    // 단 Symbol draft할 때 붙어 있는 symbol도 draft함
116
                    RunSymbolModeling();
117
                    // LineRun Line Modeling
118
                    // Line 그리는 우선 순위 
119
                    // 1. Branch 없는 것
120
                    // 2. Symbol 연결 개수
121
                    // 3. Symbol 제외 Item 연결 개수
122
                    // 4. ConnectedItem이 없는것
123
                    RunLineModeling();
124
                    // Vent Drain Modeling
125
                    // Vent/Drain으로 인식한 Item draft
126
                    // 인식 조건
127
                    // 1. ID2에서 Line이 하나며 Branch된 Line이 있고
128
                    // 2. Valve가 line에 붙어있다.
129
                    RunVentDrainModeling();
130
                    // Clear Attribute
131
                    // SPPID에서 Line 생성 시 자동으로 Nominal Diameter가 입력되는 경우가 있음
132
                    // 모든 Item의 Nominal Diameter 속성값 초기화
133
                    RunClearNominalDiameter();
134
                    // Join SameConnector
135
                    // 기존 Line을 그릴때 SPPID에서는 같은 Run으로 생성되지 않고 각각 PipeRun이 생성됨
136
                    // ID2의 EndBreak등 segmentbreak가 없으면 Line을 합침
137
                    RunJoinRunForSameConnector();
138
                    // Join Run
139
                    // 같은 Type의 Line일 경우 Join함
140
                    RunJoinRun();
141

    
142
                    // avoid interference
143
                    SetConnectorAndSymbolRange();
144
                    // EndBreak Modeling
145
                    RunEndBreakModeling();
146
                    // avoid interference
147
                    SetConnectorAndSymbolRange();
148
                    // SpecBreak Modeling
149
                    RunSpecBreakModeling();
150
                    //Line Number Modeling
151
                    // Label만 draft
152
                    RunLineNumberModeling();
153
                    // Note Modeling
154
                    RunNoteModeling();
155
                    // Text Modeling
156
                    RunTextModeling();
157
                    // Input LineNumber Attribute
158
                    RunInputLineNumberAttribute();
159
                    // Input Symbol Attribute
160
                    RunInputSymbolAttribute();
161
                    // Input SpecBreak Attribute
162
                    RunInputSpecBreakAttribute();
163
                    // Input EndBreak Attribute
164
                    RunInputEndBreakAttribute();
165
                    // Label Symbol Modeling
166
                    RunLabelSymbolModeling();
167

    
168
                    // Correct Text
169
                    // LabelPersist 정렬 로직
170
                    // 예) Valve Size label 등
171
                    RunCorrectAssociationText();
172
                    // ETC
173
                    // Label을 Front로 옮김
174
                    RunETC();
175
                    // input bulk attribute
176
                    RunBulkAttribute();
177
                    // log file 생성
178
                    document.CheckModelingResult();
179
                }
180
            }
181
            catch (Exception ex)
182
            {
183
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
184
                {
185
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
186
                    SplashScreenManager.CloseForm(false);
187
                    Log.Write("\r\n");
188
                }
189
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
190
            }
191
            finally
192
            {
193
                Project_DB.InsertDrawingInfoAndOPCInfo(document.PATH, drawingNumber, drawingName, document);
194
                //Project_DB.InsertLineNumberInfo(document.PATH, drawingNumber, drawingName, document);
195

    
196
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
197
                {
198
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
199
                    SplashScreenManager.CloseForm(false);
200
                    Log.Write("\r\n");
201
                }
202
                Thread.Sleep(1000);
203

    
204
                Log.Write("End Modeling");
205
                radApp.ActiveWindow.Fit();
206

    
207
                ReleaseCOMObjects(application);
208
                application = null;
209
                if (radApp.ActiveDocument != null)
210
                {
211
                    if (closeDocument && newDrawing != null)
212
                    {
213
                        newDrawing.Save();
214
                        newDrawing.CloseDrawing(true);
215
                        ReleaseCOMObjects(newDrawing); 
216
                        newDrawing = null;
217
                    }
218
                    else if (newDrawing == null)
219
                    {
220
                        Log.Write("error document");
221
                    }
222
                }
223

    
224
                ReleaseCOMObjects(dataSource);
225
                dataSource = null;
226
                ReleaseCOMObjects(_placement);
227
                _placement = null;
228

    
229
                Thread.Sleep(1000);
230
            }
231
        }
232

    
233
        private void RunVendorPackageModeling()
234
        {
235
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VendorPackages.Count);
236
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "VendorPackages Modeling");
237
            foreach (VendorPackage item in document.VendorPackages)
238
            {
239
                try
240
                {
241
                    VendorPackageModeling(item);
242
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
243
                }
244
                catch (Exception ex)
245
                {
246
                    Log.Write("Error in RunVendorPackageModeling");
247
                    Log.Write("UID : " + item.UID);
248
                    Log.Write(ex.Message);
249
                    Log.Write(ex.StackTrace);
250
                }
251
            }
252
        }
253
        private void RunEquipmentModeling()
254
        {
255
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
256
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
257
            for (int i = 0; i < document.Equipments.Count; i++)
258
            {
259
                Equipment item = document.Equipments[i];
260
                try
261
                {
262
                    if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
263
                        continue;
264
                    EquipmentModeling(item);
265
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
266
                    if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
267
                        i = -1;
268
                }
269
                catch (Exception ex)
270
                {
271
                    Log.Write("Error in EquipmentModeling");
272
                    Log.Write("UID : " + item.UID);
273
                    Log.Write(ex.Message);
274
                    Log.Write(ex.StackTrace);
275
                }
276
            }
277
        }
278
        private void RunSymbolModeling()
279
        {
280
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
281
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
282
            prioritySymbols = GetPrioritySymbol();
283
            foreach (var item in prioritySymbols)
284
            {
285
                try
286
                {
287
                    if (document.VentDrainSymbol.Contains(item))
288
                        continue;
289
                    SymbolModelingBySymbol(item);
290
                }
291
                catch (Exception ex)
292
                {
293
                    Log.Write("Error in SymbolModelingByPriority");
294
                    Log.Write("UID : " + item.UID);
295
                    Log.Write(ex.Message);
296
                    Log.Write(ex.StackTrace);
297
                }
298
            }
299
        }
300
        private void RunLineModeling()
301
        {
302
            List<Line> AllLine = document.LINES.ToList();
303
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
304
            !SPPIDUtil.IsBranchedLine(document, x));
305
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
306

    
307
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
308
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
309

    
310
            SetPriorityLine(step1_Line);
311
            foreach (var item in step1_Line)
312
            {
313
                try
314
                {
315
                    if (document.VentDrainLine.Contains(item))
316
                        continue;
317
                    NewLineModeling(item);
318
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
319
                }
320
                catch (Exception ex)
321
                {
322
                    Log.Write("Error in NewLineModeling");
323
                    Log.Write("UID : " + item.UID);
324
                    Log.Write(ex.Message);
325
                    Log.Write(ex.StackTrace);
326
                }
327
            }
328

    
329
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
330
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
331
            int branchCount = BranchLines.Count;
332
            while (BranchLines.Count > 0)
333
            {
334
                try
335
                {
336
                    SortBranchLines();
337
                    Line item = BranchLines[0];
338
                    NewLineModeling(item, true);
339
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
340
                }
341
                catch (Exception ex)
342
                {
343
                    Log.Write("Error in NewLineModeling");
344
                    Log.Write("UID : " + BranchLines[0].UID);
345
                    Log.Write(ex.Message);
346
                    Log.Write(ex.StackTrace);
347
                    BranchLines.Remove(BranchLines[0]);
348
                }
349
            }
350

    
351
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
352
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
353
            foreach (var item in stepLast_Line)
354
            {
355
                try
356
                {
357
                    if (document.VentDrainLine.Contains(item))
358
                        continue;
359
                    NewLineModeling(item);
360
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
361
                }
362
                catch (Exception ex)
363
                {
364
                    Log.Write("Error in NewLineModeling");
365
                    Log.Write("UID : " + item.UID);
366
                    Log.Write(ex.Message);
367
                    Log.Write(ex.StackTrace);
368
                }
369
            }
370
        }
371
        private void RunVentDrainModeling()
372
        {
373
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VentDrainLine.Count);
374
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Vent Drain Modeling");
375
            foreach (var item in document.VentDrainLine)
376
            {
377
                try
378
                {
379
                    Connector connector = item.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
380
                    if (connector != null)
381
                    {
382
                        SetCoordinate();
383
                        Symbol connSymbol = connector.ConnectedObject as Symbol;
384
                        SymbolModeling(connSymbol, null);
385
                        NewLineModeling(item, true);
386

    
387
                        GridSetting grid = GridSetting.GetInstance();
388
                        int count = grid.DrainValveCellCount;
389
                        double length = grid.Length;
390

    
391
                        // 길이 확인
392
                        if (!string.IsNullOrEmpty(item.SPPID.ModelItemId))
393
                        {
394
                            LMConnector _LMConnector = GetLMConnectorOnlyOne(item.SPPID.ModelItemId);
395
                            if (_LMConnector != null)
396
                            {
397
                                double[] connectorRange = GetConnectorRange(_LMConnector);
398
                                double connectorLength = double.NaN;
399
                                if (item.SlopeType == SlopeType.HORIZONTAL)
400
                                    connectorLength = connectorRange[2] - connectorRange[0];
401
                                else if (item.SlopeType == SlopeType.VERTICAL)
402
                                    connectorLength = connectorRange[3] - connectorRange[1];
403

    
404
                                if (!double.IsNaN(connectorLength) && connectorLength != count * length)
405
                                {
406
                                    double move = count * length - connectorLength;
407
                                    List<Symbol> group = new List<Symbol>();
408
                                    SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
409
                                    foreach (var symbol in group)
410
                                    {
411
                                        int connSymbolIndex = item.CONNECTORS.IndexOf(item.CONNECTORS.Find(x => x.ConnectedObject == connSymbol));
412
                                        if (item.SlopeType == SlopeType.HORIZONTAL)
413
                                        {
414
                                            if (connSymbolIndex == 0)
415
                                            {
416
                                                if (item.SPPID.START_X > item.SPPID.END_X)
417
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
418
                                                else
419
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
420
                                            }
421
                                            else
422
                                            {
423
                                                if (item.SPPID.START_X < item.SPPID.END_X)
424
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
425
                                                else
426
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
427
                                            }
428
                                        }
429
                                        else if (item.SlopeType == SlopeType.VERTICAL)
430
                                        {
431
                                            if (connSymbolIndex == 0)
432
                                            {
433
                                                if (item.SPPID.START_Y > item.SPPID.END_Y)
434
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
435
                                                else
436
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
437
                                            }
438
                                            else
439
                                            {
440
                                                if (item.SPPID.START_Y < item.SPPID.END_Y)
441
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
442
                                                else
443
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
444
                                            }
445
                                        }
446
                                    }
447

    
448
                                    // 제거
449
                                    RemoveSymbol(connSymbol);
450
                                    RemoveLine(item);
451

    
452
                                    // 재생성
453
                                    SymbolModelingBySymbol(connSymbol);
454
                                    NewLineModeling(item, true);
455
                                }
456
                            }
457

    
458
                            ReleaseCOMObjects(_LMConnector);
459
                            _LMConnector = null;
460
                        }
461
                    }
462
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
463
                }
464
                catch (Exception ex)
465
                {
466
                    Log.Write("Error in NewLineModeling");
467
                    Log.Write("UID : " + item.UID);
468
                    Log.Write(ex.Message);
469
                    Log.Write(ex.StackTrace);
470
                }
471

    
472
                void SetCoordinate()
473
                {
474
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
475
                    if (branchConnector != null)
476
                    {
477
                        Line connLine = branchConnector.ConnectedObject as Line;
478
                        double x = 0;
479
                        double y = 0;
480
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
481
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
482
                        if (targetConnector != null)
483
                        {
484
                            List<Symbol> group = new List<Symbol>();
485
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
486
                            if (item.SlopeType == SlopeType.HORIZONTAL)
487
                            {
488
                                item.SPPID.START_Y = y;
489
                                item.SPPID.END_Y = y;
490
                                foreach (var symbol in group)
491
                                {
492
                                    symbol.SPPID.ORIGINAL_Y = y;
493
                                    symbol.SPPID.SPPID_Y = y;
494
                                }
495
                            }
496
                            else if (item.SlopeType == SlopeType.VERTICAL)
497
                            {
498
                                item.SPPID.START_X = x;
499
                                item.SPPID.END_X = x;
500
                                foreach (var symbol in group)
501
                                {
502
                                    symbol.SPPID.ORIGINAL_X = x;
503
                                    symbol.SPPID.SPPID_X = x;
504
                                }
505
                            }
506
                        }
507
                        ReleaseCOMObjects(targetConnector);
508
                        targetConnector = null;
509
                    }
510
                }
511
            }
512
        }
513
        private void RunClearNominalDiameter()
514
        {
515
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
516
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
517
            return;
518

    
519
            List<string> endClearModelItemID = new List<string>();
520
            for (int i = 0; i < document.LINES.Count; i++)
521
            {
522
                Line item = document.LINES[i];
523
                string modelItemID = item.SPPID.ModelItemId;
524
                if (!string.IsNullOrEmpty(modelItemID))
525
                {
526
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
527
                    if (modelItem != null)
528
                    {
529
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
530
                        if (attribute != null)
531
                            attribute.set_Value(DBNull.Value);
532

    
533
                        modelItem.Commit();
534
                        ReleaseCOMObjects(modelItem);
535
                        modelItem = null;
536
                    }
537
                }
538
                if (!endClearModelItemID.Contains(modelItemID))
539
                    endClearModelItemID.Add(modelItemID);
540
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
541
            }
542
            for (int i = 0; i < document.SYMBOLS.Count; i++)
543
            {
544
                Symbol item = document.SYMBOLS[i];
545
                string repID = item.SPPID.RepresentationId;
546
                string modelItemID = item.SPPID.ModelItemID;
547
                if (!string.IsNullOrEmpty(modelItemID))
548
                {
549
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
550
                    if (modelItem != null)
551
                    {
552
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
553
                        if (attribute != null)
554
                            attribute.set_Value(DBNull.Value);
555
                        int index = 1;
556
                        while (true)
557
                        {
558
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
559
                            if (attribute != null)
560
                                attribute.set_Value(DBNull.Value);
561
                            else
562
                                break;
563
                            index++;
564
                        }
565
                        modelItem.Commit();
566
                        ReleaseCOMObjects(modelItem);
567
                        modelItem = null;
568
                    }
569
                }
570
                if (!string.IsNullOrEmpty(repID))
571
                {
572
                    LMSymbol symbol = dataSource.GetSymbol(repID);
573
                    if (symbol != null)
574
                    {
575
                        foreach (LMConnector connector in symbol.Connect1Connectors)
576
                        {
577
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
578
                            {
579
                                endClearModelItemID.Add(connector.ModelItemID);
580
                                LMModelItem modelItem = connector.ModelItemObject;
581
                                if (modelItem != null)
582
                                {
583
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
584
                                    if (attribute != null)
585
                                        attribute.set_Value(DBNull.Value);
586

    
587
                                    modelItem.Commit();
588
                                    ReleaseCOMObjects(modelItem);
589
                                    modelItem = null;
590
                                }
591
                            }
592
                        }
593
                        foreach (LMConnector connector in symbol.Connect2Connectors)
594
                        {
595
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
596
                            {
597
                                endClearModelItemID.Add(connector.ModelItemID);
598
                                LMModelItem modelItem = connector.ModelItemObject;
599
                                if (modelItem != null)
600
                                {
601
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
602
                                    if (attribute != null)
603
                                        attribute.set_Value(DBNull.Value);
604

    
605
                                    modelItem.Commit();
606
                                    ReleaseCOMObjects(modelItem);
607
                                    modelItem = null;
608
                                }
609
                            }
610
                        }
611
                    }
612
                    ReleaseCOMObjects(symbol);
613
                    symbol = null;
614
                }
615
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
616
            }
617
        }
618
        private void RunClearValueInconsistancy()
619
        {
620
            int count = 1;
621
            bool loop = true;
622
            while (loop)
623
            {
624
                loop = false;
625
                LMAFilter filter = new LMAFilter();
626
                LMACriterion criterion = new LMACriterion();
627
                filter.ItemType = "Relationship";
628
                criterion.SourceAttributeName = "SP_DRAWINGID";
629
                criterion.Operator = "=";
630
                criterion.set_ValueAttribute(drawingID);
631
                filter.get_Criteria().Add(criterion);
632

    
633
                LMRelationships relationships = new LMRelationships();
634
                relationships.Collect(dataSource, Filter: filter);
635

    
636
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
637
                if (count > 1)
638
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
639
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
640
                foreach (LMRelationship relationship in relationships)
641
                {
642
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
643
                    {
644
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
645
                        {
646
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
647
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
648
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
649
                            if (modelItem1 != null)
650
                            {
651
                                string attrName = array[0];
652
                                if (attrName.Contains("PipingPoint"))
653
                                {
654
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
655
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
656
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
657
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
658
                                    {
659
                                        loop = true;
660
                                        attribute1.set_Value(DBNull.Value);
661
                                    }
662
                                    attribute1 = null;
663
                                }
664
                                else
665
                                {
666
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
667
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
668
                                    {
669
                                        loop = true;
670
                                        attribute1.set_Value(DBNull.Value);
671
                                    }
672
                                    attribute1 = null;
673
                                }
674
                                modelItem1.Commit();
675
                            }
676
                            if (modelItem2 != null)
677
                            {
678
                                string attrName = array[1];
679
                                if (attrName.Contains("PipingPoint"))
680
                                {
681
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
682
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
683
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
684
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
685
                                    {
686
                                        attribute2.set_Value(DBNull.Value);
687
                                        loop = true;
688
                                    }
689
                                    attribute2 = null;
690
                                }
691
                                else
692
                                {
693
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
694
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
695
                                    {
696
                                        attribute2.set_Value(DBNull.Value);
697
                                        loop = true;
698
                                    }
699
                                    attribute2 = null;
700
                                }
701
                                modelItem2.Commit();
702
                            }
703
                            ReleaseCOMObjects(modelItem1);
704
                            modelItem1 = null;
705
                            ReleaseCOMObjects(modelItem2);
706
                            modelItem2 = null;
707
                            inconsistency.Commit();
708
                        }
709
                        ReleaseCOMObjects(inconsistency);
710
                    }
711
                    relationship.Commit();
712
                    ReleaseCOMObjects(relationship);
713
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
714
                }
715
                ReleaseCOMObjects(filter);
716
                filter = null;
717
                ReleaseCOMObjects(criterion);
718
                criterion = null;
719
                ReleaseCOMObjects(relationships);
720
                relationships = null;
721
                count++;
722
            }
723
        }
724
        private void RunEndBreakModeling()
725
        {
726
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
727
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
728
            foreach (var item in document.EndBreaks)
729
                try
730
                {
731
                    EndBreakModeling(item);
732
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
733
                }
734
                catch (Exception ex)
735
                {
736
                    Log.Write("Error in EndBreakModeling");
737
                    Log.Write("UID : " + item.UID);
738
                    Log.Write(ex.Message);
739
                    Log.Write(ex.StackTrace);
740
                }
741
        }
742
        private void RunSpecBreakModeling()
743
        {
744
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
745
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
746
            foreach (var item in document.SpecBreaks)
747
                try
748
                {
749
                    SpecBreakModeling(item);
750
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
751
                }
752
                catch (Exception ex)
753
                {
754
                    Log.Write("Error in SpecBreakModeling");
755
                    Log.Write("UID : " + item.UID);
756
                    Log.Write(ex.Message);
757
                    Log.Write(ex.StackTrace);
758
                }
759
        }
760
        private void RunJoinRunForSameConnector()
761
        {
762
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
763
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
764
            foreach (var line in document.LINES)
765
            {
766
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
767
                List<List<double[]>> result = new List<List<double[]>>();
768
                foreach (var item in vertices)
769
                {
770
                    ReleaseCOMObjects(item.Key);
771
                    result.Add(item.Value);
772
                }
773
                line.SPPID.Vertices = result;
774
                vertices = null;
775
            }
776

    
777
            foreach (var line in document.LINES)
778
            {
779
                foreach (var connector in line.CONNECTORS)
780
                {
781
                    if (connector.ConnectedObject != null &&
782
                        connector.ConnectedObject.GetType() == typeof(Line) &&
783
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
784
                    {
785
                        Line connLine = connector.ConnectedObject as Line;
786
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
787
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
788
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
789
                            !SPPIDUtil.IsSegment(document, line, connLine))
790
                        {
791
                            string survivorId = string.Empty;
792
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
793
                        }
794

    
795
                    }
796
                }
797
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
798
            }
799

    
800
            foreach (var line in document.LINES)
801
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
802
        }
803
        private void RunJoinRun()
804
        {
805
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
806
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
807
            List<string> endModelID = new List<string>();
808
            foreach (var line in document.LINES)
809
            {
810
                if (!endModelID.Contains(line.SPPID.ModelItemId))
811
                {
812
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
813
                    {
814
                        string survivorId = string.Empty;
815
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
816
                        if (string.IsNullOrEmpty(survivorId))
817
                        {
818
                            endModelID.Add(line.SPPID.ModelItemId);
819
                        }
820
                    }
821
                }
822
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
823
            }
824
        }
825
        private void RunLineNumberModeling()
826
        {
827
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
828
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
829
            foreach (var item in document.LINENUMBERS)
830
            {
831
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
832
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
833
                {
834
                    ReleaseCOMObjects(label);
835
                    item.SPPID.RepresentationId = null;
836
                    LineNumberModeling(item);
837
                }
838
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
839
            }
840
        }
841
        private void RunNoteModeling()
842
        {
843
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
844
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
845
            List<Note> correctList = new List<Note>();
846
            foreach (var item in document.NOTES)
847
                try
848
                {
849
                    NoteModeling(item, correctList);
850
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
851
                }
852
                catch (Exception ex)
853
                {
854
                    Log.Write("Error in NoteModeling");
855
                    Log.Write("UID : " + item.UID);
856
                    Log.Write(ex.Message);
857
                    Log.Write(ex.StackTrace);
858
                }
859

    
860
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
861
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
862
            SortNote(correctList);
863
            List<Note> endList = new List<Note>();
864
            if (correctList.Count > 0)
865
                endList.Add(correctList[0]);
866
            foreach (var item in correctList)
867
                try
868
                {
869
                    if (!endList.Contains(item))
870
                        NoteCorrectModeling(item, endList);
871
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
872
                }
873
                catch (Exception ex)
874
                {
875
                    Log.Write("Error in NoteModeling");
876
                    Log.Write("UID : " + item.UID);
877
                    Log.Write(ex.Message);
878
                    Log.Write(ex.StackTrace);
879
                }
880
        }
881
        private void RunTextModeling()
882
        {
883
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
884
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
885
            SortText(document.TEXTINFOS);
886
            foreach (var item in document.TEXTINFOS)
887
                try
888
                {
889
                    if (item.ASSOCIATION)
890
                        AssociationTextModeling(item);
891
                    else
892
                        NormalTextModeling(item);
893
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
894
                }
895
                catch (Exception ex)
896
                {
897
                    Log.Write("Error in TextModeling");
898
                    Log.Write("UID : " + item.UID);
899
                    Log.Write(ex.Message);
900
                    Log.Write(ex.StackTrace);
901
                }
902
        }
903
        private void RunInputLineNumberAttribute()
904
        {
905
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
906
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
907
            List<string> endLine = new List<string>();
908
            foreach (var item in document.LINENUMBERS)
909
                try
910
                {
911
                    InputLineNumberAttribute(item, endLine);
912
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
913
                }
914
                catch (Exception ex)
915
                {
916
                    Log.Write("Error in InputLineNumberAttribute");
917
                    Log.Write("UID : " + item.UID);
918
                    Log.Write(ex.Message);
919
                    Log.Write(ex.StackTrace);
920
                }
921
        }
922
        private void RunInputSymbolAttribute()
923
        {
924
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.Equipments.Count + document.LINES.Count);
925
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
926
            foreach (var item in document.SYMBOLS)
927
                try
928
                {
929
                    InputSymbolAttribute(item, item.ATTRIBUTES);
930
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
931
                }
932
                catch (Exception ex)
933
                {
934
                    Log.Write("Error in InputSymbolAttribute");
935
                    Log.Write("UID : " + item.UID);
936
                    Log.Write(ex.Message);
937
                    Log.Write(ex.StackTrace);
938
                }
939

    
940
            foreach (var item in document.Equipments)
941
                try
942
                {
943
                    InputSymbolAttribute(item, item.ATTRIBUTES);
944
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
945
                }
946
                catch (Exception ex)
947
                {
948
                    Log.Write("Error in InputSymbolAttribute");
949
                    Log.Write("UID : " + item.UID);
950
                    Log.Write(ex.Message);
951
                    Log.Write(ex.StackTrace);
952
                }
953
            foreach (var item in document.LINES)
954
                try
955
                {
956
                    InputSymbolAttribute(item, item.ATTRIBUTES);
957
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
958
                }
959
                catch (Exception ex)
960
                {
961
                    Log.Write("Error in InputSymbolAttribute");
962
                    Log.Write("UID : " + item.UID);
963
                    Log.Write(ex.Message);
964
                    Log.Write(ex.StackTrace);
965
                }
966
        }
967
        private void RunInputSpecBreakAttribute()
968
        {
969
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
970
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
971
            foreach (var item in document.SpecBreaks)
972
                try
973
                {
974
                    InputSpecBreakAttribute(item);
975
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
976
                }
977
                catch (Exception ex)
978
                {
979
                    Log.Write("Error in InputSpecBreakAttribute");
980
                    Log.Write("UID : " + item.UID);
981
                    Log.Write(ex.Message);
982
                    Log.Write(ex.StackTrace);
983
                }
984
        }
985
        private void RunInputEndBreakAttribute()
986
        {
987
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
988
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
989
            foreach (var item in document.EndBreaks)
990
                try
991
                {
992
                    InputEndBreakAttribute(item);
993
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
994
                }
995
                catch (Exception ex)
996
                {
997
                    Log.Write("Error in RunInputEndBreakAttribute");
998
                    Log.Write("UID : " + item.UID);
999
                    Log.Write(ex.Message);
1000
                    Log.Write(ex.StackTrace);
1001
                }
1002
        }
1003
        private void RunLabelSymbolModeling()
1004
        {
1005
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
1006
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
1007
            foreach (var item in document.SYMBOLS)
1008
                try
1009
                {
1010
                    LabelSymbolModeling(item);
1011
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1012
                }
1013
                catch (Exception ex)
1014
                {
1015
                    Log.Write("Error in LabelSymbolModeling");
1016
                    Log.Write("UID : " + item.UID);
1017
                    Log.Write(ex.Message);
1018
                    Log.Write(ex.StackTrace);
1019
                }
1020

    
1021
        }
1022
        private void RunCorrectAssociationText()
1023
        {
1024
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
1025
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
1026
            List<Text> endTexts = new List<Text>();
1027
            foreach (var item in document.TEXTINFOS)
1028
            {
1029
                try
1030
                {
1031
                    if (item.ASSOCIATION && !endTexts.Contains(item))
1032
                        AssociationTextCorrectModeling(item, endTexts);
1033
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1034
                }
1035
                catch (Exception ex)
1036
                {
1037
                    Log.Write("Error in RunCorrectAssociationText");
1038
                    Log.Write("UID : " + item.UID);
1039
                    Log.Write(ex.Message);
1040
                    Log.Write(ex.StackTrace);
1041
                }
1042

    
1043
            }
1044

    
1045
            foreach (var item in document.LINENUMBERS)
1046
            {
1047
                try
1048
                {
1049
                    LineNumberCorrectModeling(item);
1050
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1051
                }
1052
                catch (Exception ex)
1053
                {
1054
                    Log.Write("Error in RunCorrectAssociationText");
1055
                    Log.Write("UID : " + item.UID);
1056
                    Log.Write(ex.Message);
1057
                    Log.Write(ex.StackTrace);
1058
                }
1059
            }
1060
        }
1061
        private void RunETC()
1062
        {
1063
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, FlowMarkRepIds.Count);
1064
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "ETC");
1065
            foreach (var item in FlowMarkRepIds)
1066
            {
1067
                LMLabelPersist label = dataSource.GetLabelPersist(item);
1068
                if (label != null)
1069
                {
1070
                    label.get_GraphicOID();
1071
                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[label.get_GraphicOID().ToString()] as DependencyObject;
1072
                    if (dependency != null)
1073
                        dependency.BringToFront();
1074
                }
1075
                ReleaseCOMObjects(label);
1076
                label = null;
1077
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1078
            }
1079
        }
1080
        private void RunBulkAttribute()
1081
        {
1082
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 2);
1083
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Bulk Attribute");
1084

    
1085
            List<SPPIDModel.BulkAttribute> select = _ETCSetting.BulkAttributes.FindAll(x => x.RuleName.Equals(document.BulkAttributeName));
1086
            if (select.Count > 0)
1087
                SPPIDUtil.BulkAttribute(dataSource, select, BulkAttributeItemType.PipeRun);
1088
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1089
            if (select.Count > 0)
1090
                SPPIDUtil.BulkAttribute(dataSource, select, BulkAttributeItemType.Symbol);
1091
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1092
        }
1093
        /// <summary>
1094
        /// 도면 생성 메서드
1095
        /// </summary>
1096
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1097
        {
1098
            Log.Write("------------------ Start create document ------------------");
1099
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1100
            Log.Write("Drawing name : " + drawingName);
1101
            Log.Write("Drawing number : " + drawingNumber);
1102
            Thread.Sleep(1000);
1103
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1104
            if (newDrawing != null)
1105
            {
1106
                document.SPPID_DrawingNumber = drawingNumber;
1107
                document.SPPID_DrawingName = drawingName;
1108
                Thread.Sleep(1000);
1109
                radApp.ActiveWindow.Fit();
1110
                Thread.Sleep(1000);
1111
                radApp.ActiveWindow.Zoom = 2000;
1112
                Thread.Sleep(2000);
1113

    
1114
                //current LMDrawing 가져오기
1115
                LMAFilter filter = new LMAFilter();
1116
                LMACriterion criterion = new LMACriterion();
1117
                filter.ItemType = "Drawing";
1118
                criterion.SourceAttributeName = "Name";
1119
                criterion.Operator = "=";
1120
                criterion.set_ValueAttribute(drawingName);
1121
                filter.get_Criteria().Add(criterion);
1122

    
1123
                LMDrawings drawings = new LMDrawings();
1124
                drawings.Collect(dataSource, Filter: filter);
1125

    
1126
                // Input Drawing Attribute
1127
                LMDrawing drawing = ((dynamic)drawings).Nth(1);
1128
                if (drawing != null)
1129
                {
1130
                    using (DataTable drawingAttributeDT = Project_DB.SelectDrawingProjectAttribute())
1131
                    {
1132
                        foreach (DataRow row in drawingAttributeDT.Rows)
1133
                        {
1134
                            string mappingName = DBNull.Value.Equals(row["SPPID_ATTRIBUTE"]) ? string.Empty : row["SPPID_ATTRIBUTE"].ToString();
1135
                            if (!string.IsNullOrEmpty(mappingName))
1136
                            {
1137
                                string uid = row["UID"].ToString();
1138
                                string name = row["NAME"].ToString();
1139
                                Text text = document.TEXTINFOS.Find(x => x.AREA == uid);
1140
                                if (text != null)
1141
                                {
1142
                                    string value = text.VALUE;
1143
                                    LMAAttribute attribute = drawing.Attributes[mappingName];
1144
                                    if (attribute != null)
1145
                                        attribute.set_Value(value);
1146
                                    ReleaseCOMObjects(attribute);
1147
                                    document.TEXTINFOS.Remove(text);
1148
                                }
1149
                            }
1150
                        }
1151

    
1152
                        drawingAttributeDT.Dispose();
1153
                    }
1154

    
1155
                    ReleaseCOMObjects(drawing);
1156
                }
1157

    
1158
                drawingID = ((dynamic)drawings).Nth(1).Id;
1159
                ReleaseCOMObjects(filter);
1160
                ReleaseCOMObjects(criterion);
1161
                ReleaseCOMObjects(drawings);
1162
                filter = null;
1163
                criterion = null;
1164
                drawings = null;
1165
            }
1166
            else
1167
                Log.Write("Fail Create Drawing");
1168

    
1169
            if (newDrawing != null)
1170
            {
1171
                SetBorderFile();
1172
                return true;
1173
            }
1174
            else
1175
                return false;
1176
        }
1177

    
1178
        private void SetBorderFile()
1179
        {
1180
            ETCSetting setting = ETCSetting.GetInstance();
1181

    
1182
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1183
            {
1184
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1185
                {
1186
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1187
                    {
1188
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1189
                        smartFrame.Update();
1190
                    }
1191

    
1192
                }
1193
            }
1194
        }
1195

    
1196
        /// <summary>
1197
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1198
        /// </summary>
1199
        /// <param name="drawingName"></param>
1200
        /// <param name="drawingNumber"></param>
1201
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1202
        {
1203
            LMDrawings drawings = new LMDrawings();
1204
            drawings.Collect(dataSource);
1205

    
1206
            List<string> drawingNameList = new List<string>();
1207
            List<string> drawingNumberList = new List<string>();
1208

    
1209
            foreach (LMDrawing item in drawings)
1210
            {
1211
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1212
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1213
            }
1214

    
1215
            int nameLength = drawingName.Length;
1216
            while (drawingNameList.Contains(drawingName))
1217
            {
1218
                if (nameLength == drawingName.Length)
1219
                    drawingName += "-1";
1220
                else
1221
                {
1222
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1223
                    drawingName = drawingName.Substring(0, nameLength + 1);
1224
                    drawingName += ++index;
1225
                }
1226
            }
1227

    
1228
            int numberLength = drawingNumber.Length;
1229
            while (drawingNameList.Contains(drawingNumber))
1230
            {
1231
                if (numberLength == drawingNumber.Length)
1232
                    drawingNumber += "-1";
1233
                else
1234
                {
1235
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1236
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1237
                    drawingNumber += ++index;
1238
                }
1239
            }
1240
            ReleaseCOMObjects(drawings);
1241
            drawings = null;
1242
        }
1243

    
1244
        /// <summary>
1245
        /// 도면 크기 구하는 메서드
1246
        /// </summary>
1247
        /// <returns></returns>
1248
        private bool DocumentCoordinateCorrection()
1249
        {
1250
            //if (radApp.ActiveDocument.ActiveSheet.SmartFrames2d.Count > 0)
1251
            //{
1252
            //    double x = 0;
1253
            //    double y = 0;
1254
            //    foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1255
            //    {
1256
            //        x = Math.Max(smartFrame.CropRight, x);
1257
            //        y = Math.Max(smartFrame.CropTop, y);
1258
            //    }
1259
            //    document.SetSPPIDLocation(x, y);
1260
            //    document.CoordinateCorrection();
1261
            //    return true;
1262
            //}
1263
            //else
1264
            //{
1265
            //    Log.Write("Need Border!");
1266
            //    return false;
1267
            //}
1268

    
1269
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1270
            {
1271
                Log.Write("Setting Drawing X, Drawing Y");
1272
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1273
                Log.Write("Start coordinate correction");
1274
                document.CoordinateCorrection();
1275
                return true;
1276
            }
1277
            else
1278
            {
1279
                Log.Write("Need Drawing X, Y");
1280
                return false;
1281
            }
1282
        }
1283

    
1284
        /// <summary>
1285
        /// 심볼을 실제로 Modeling 메서드
1286
        /// </summary>
1287
        /// <param name="symbol">생성할 심볼</param>
1288
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1289
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1290
        {
1291
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1292
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1293
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1294
                return;
1295
            // 이미 모델링 됐을 경우
1296
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1297
                return;
1298

    
1299
            LMSymbol _LMSymbol = null;
1300

    
1301
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1302
            double x = symbol.SPPID.ORIGINAL_X;
1303
            double y = symbol.SPPID.ORIGINAL_Y;
1304
            int mirror = 0;
1305
            double angle = symbol.ANGLE;
1306

    
1307
            // OPC 일경우 180도 일때 Mirror
1308
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1309
                mirror = 1;
1310

    
1311
            // Mirror 계산
1312
            if (symbol.FLIP == 1)
1313
            {
1314
                mirror = 1;
1315
                if (angle == Math.PI || angle == 0)
1316
                    angle += Math.PI;
1317
            }
1318

    
1319
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1320
            {
1321
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1322
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1323
                if (connector != null)
1324
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1325

    
1326
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1327
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1328
                if (temp != null)
1329
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1330
                ReleaseCOMObjects(temp);
1331
                temp = null;
1332

    
1333
                if (_LMSymbol != null && _TargetItem != null)
1334
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1335

    
1336
                ReleaseCOMObjects(_TargetItem);
1337
            }
1338
            else
1339
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1340

    
1341
            if (_LMSymbol != null)
1342
            {
1343
                _LMSymbol.Commit();
1344

    
1345
                // ConnCheck
1346
                List<string> ids = new List<string>();
1347
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1348
                {
1349
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1350
                        ids.Add(item.Id);
1351
                    ReleaseCOMObjects(item);
1352
                }
1353
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1354
                {
1355
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1356
                        ids.Add(item.Id);
1357
                    ReleaseCOMObjects(item);
1358
                }
1359

    
1360
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1361
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1362
                {
1363
                    double currentX = _LMSymbol.get_XCoordinate();
1364
                    double currentY = _LMSymbol.get_YCoordinate();
1365

    
1366

    
1367
                }
1368

    
1369
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1370
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1371
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1372

    
1373
                foreach (var item in symbol.ChildSymbols)
1374
                    CreateChildSymbol(item, _LMSymbol, symbol);
1375

    
1376
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1377
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1378

    
1379
                double[] range = null;
1380
                GetSPPIDSymbolRange(symbol, ref range);
1381
                symbol.SPPID.SPPID_Min_X = range[0];
1382
                symbol.SPPID.SPPID_Min_Y = range[1];
1383
                symbol.SPPID.SPPID_Max_X = range[2];
1384
                symbol.SPPID.SPPID_Max_Y = range[3];
1385

    
1386
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1387
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1388
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1389
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1390

    
1391
                ReleaseCOMObjects(_LMSymbol);
1392
            }
1393
        }
1394
        /// <summary>
1395
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1396
        /// Signal Point는 고려하지 않음
1397
        /// </summary>
1398
        /// <param name="symbol"></param>
1399
        /// <param name="_TargetItem"></param>
1400
        /// <param name="targetX"></param>
1401
        /// <param name="targetY"></param>
1402
        /// <returns></returns>
1403
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1404
        {
1405
            LMConnector tempConnector = null;
1406

    
1407
            List<Symbol> group = new List<Symbol>();
1408
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1409
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1410
            {
1411
                List<Connector> connectors = new List<Connector>();
1412
                foreach (var item in group)
1413
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1414
                /// Primary or Secondary Type Line만 고려
1415
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1416
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1417
                if (_connector != null)
1418
                {
1419
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1420
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1421
                    /// PipingPoint가 2개 이상만
1422
                    if (pointInfos.Count >= 2)
1423
                    {
1424
                        double lineX = 0;
1425
                        double lineY = 0;
1426
                        double length = 0;
1427
                        foreach (var item in pointInfos)
1428
                        {
1429
                            double tempX = item[1];
1430
                            double tempY = item[2];
1431

    
1432
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1433
                            if (calcDistance > length)
1434
                            {
1435
                                lineX = tempX;
1436
                                lineY = tempY;
1437
                            }
1438
                        }
1439

    
1440
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1441
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1442
                        placeRunInputs.AddPoint(-1, -1);
1443
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1444
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1445
                        if (tempConnector != null)
1446
                            tempConnector.Commit();
1447
                        ReleaseCOMObjects(_LMAItem);
1448
                        _LMAItem = null;
1449
                        ReleaseCOMObjects(placeRunInputs);
1450
                        placeRunInputs = null;
1451
                    }
1452
                }
1453
            }
1454

    
1455
            return tempConnector;
1456
        }
1457
        /// <summary>
1458
        /// Symbol의 PipingPoints를 구함
1459
        /// SignalPoint는 고려하지 않음
1460
        /// </summary>
1461
        /// <param name="symbol"></param>
1462
        /// <returns></returns>
1463
        private List<double[]> getPipingPoints(LMSymbol symbol)
1464
        {
1465
            LMModelItem modelItem = symbol.ModelItemObject;
1466
            LMPipingPoints pipingPoints = null;
1467
            if (modelItem.get_ItemTypeName() == "PipingComp")
1468
            {
1469
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1470
                pipingPoints = pipingComp.PipingPoints;
1471
                ReleaseCOMObjects(pipingComp);
1472
                pipingComp = null;
1473
            }
1474
            else if (modelItem.get_ItemTypeName() == "Instrument")
1475
            {
1476
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1477
                pipingPoints = instrument.PipingPoints;
1478
                ReleaseCOMObjects(instrument);
1479
                instrument = null;
1480
            }
1481
            else
1482
                Log.Write("다른 Type");
1483

    
1484
            List<double[]> info = new List<double[]>();
1485
            if (pipingPoints != null)
1486
            {
1487
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1488
                {
1489
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1490
                    {
1491
                        if (attribute.Name == "PipingPointNumber")
1492
                        {
1493
                            int index = Convert.ToInt32(attribute.get_Value());
1494
                            if (info.Find(loopX => loopX[0] == index) == null)
1495
                            {
1496
                                double x = 0;
1497
                                double y = 0;
1498
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1499
                                    info.Add(new double[] { index, x, y });
1500
                            }
1501
                        }
1502
                    }
1503
                }
1504
            }
1505
            ReleaseCOMObjects(modelItem);
1506
            modelItem = null;
1507
            ReleaseCOMObjects(pipingPoints);
1508
            pipingPoints = null;
1509

    
1510
            return info;
1511
        }
1512

    
1513
        private void RemoveSymbol(Symbol symbol)
1514
        {
1515
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1516
            {
1517
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1518
                if (_LMSymbol != null)
1519
                {
1520
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1521
                    ReleaseCOMObjects(_LMSymbol);
1522
                }
1523
            }
1524

    
1525
            symbol.SPPID.RepresentationId = string.Empty;
1526
            symbol.SPPID.ModelItemID = string.Empty;
1527
            symbol.SPPID.SPPID_X = double.NaN;
1528
            symbol.SPPID.SPPID_Y = double.NaN;
1529
            symbol.SPPID.SPPID_Min_X = double.NaN;
1530
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1531
            symbol.SPPID.SPPID_Max_X = double.NaN;
1532
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1533
        }
1534

    
1535
        private void RemoveSymbol(List<Symbol> symbols)
1536
        {
1537
            foreach (var symbol in symbols)
1538
            {
1539
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1540
                {
1541
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1542
                    if (_LMSymbol != null)
1543
                    {
1544
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1545
                        ReleaseCOMObjects(_LMSymbol);
1546
                    }
1547
                }
1548

    
1549
                symbol.SPPID.RepresentationId = string.Empty;
1550
                symbol.SPPID.ModelItemID = string.Empty;
1551
                symbol.SPPID.SPPID_X = double.NaN;
1552
                symbol.SPPID.SPPID_Y = double.NaN;
1553
                symbol.SPPID.SPPID_Min_X = double.NaN;
1554
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1555
                symbol.SPPID.SPPID_Max_X = double.NaN;
1556
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1557
            }
1558
        }
1559

    
1560
        /// <summary>
1561
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1562
        /// </summary>
1563
        /// <param name="targetConnector"></param>
1564
        /// <param name="targetSymbol"></param>
1565
        /// <param name="x"></param>
1566
        /// <param name="y"></param>
1567
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1568
        {
1569
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1570

    
1571
            double[] range = null;
1572
            List<double[]> points = new List<double[]>();
1573
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1574
            double x1 = range[0];
1575
            double y1 = range[1];
1576
            double x2 = range[2];
1577
            double y2 = range[3];
1578

    
1579
            // Origin 기준 Connector의 위치차이
1580
            double sceneX = 0;
1581
            double sceneY = 0;
1582
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1583
            double originX = 0;
1584
            double originY = 0;
1585
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1586
            double gapX = originX - sceneX;
1587
            double gapY = originY - sceneY;
1588

    
1589
            // SPPID Symbol과 ID2 심볼의 크기 차이
1590
            double sizeWidth = 0;
1591
            double sizeHeight = 0;
1592
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1593
            if (sizeWidth == 0 || sizeHeight == 0)
1594
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1595

    
1596
            double percentX = (x2 - x1) / sizeWidth;
1597
            double percentY = (y2 - y1) / sizeHeight;
1598

    
1599
            double SPPIDgapX = gapX * percentX;
1600
            double SPPIDgapY = gapY * percentY;
1601

    
1602
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1603
            double distance = double.MaxValue;
1604
            double[] resultPoint;
1605
            foreach (var point in points)
1606
            {
1607
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1608
                if (distance > result)
1609
                {
1610
                    distance = result;
1611
                    resultPoint = point;
1612
                    x = point[0];
1613
                    y = point[1];
1614
                }
1615
            }
1616

    
1617
            ReleaseCOMObjects(_TargetItem);
1618
        }
1619

    
1620
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1621
        {
1622
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1623
            if (index == 0)
1624
            {
1625
                x = targetLine.SPPID.START_X;
1626
                y = targetLine.SPPID.START_Y;
1627
            }
1628
            else
1629
            {
1630
                x = targetLine.SPPID.END_X;
1631
                y = targetLine.SPPID.END_Y;
1632
            }
1633
        }
1634

    
1635
        /// <summary>
1636
        /// SPPID Symbol의 Range를 구한다.
1637
        /// </summary>
1638
        /// <param name="symbol"></param>
1639
        /// <param name="range"></param>
1640
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1641
        {
1642
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1643
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1644
            double x1 = 0;
1645
            double y1 = 0;
1646
            double x2 = 0;
1647
            double y2 = 0;
1648
            symbol2d.Range(out x1, out y1, out x2, out y2);
1649
            range = new double[] { x1, y1, x2, y2 };
1650

    
1651
            for (int i = 1; i < 30; i++)
1652
            {
1653
                double connX = 0;
1654
                double connY = 0;
1655
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1656
                    points.Add(new double[] { connX, connY });
1657
            }
1658

    
1659
            foreach (var childSymbol in symbol.ChildSymbols)
1660
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1661

    
1662
            ReleaseCOMObjects(_TargetItem);
1663
        }
1664

    
1665
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1666
        {
1667
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1668
            if (_TargetItem != null)
1669
            {
1670
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1671
                double x1 = 0;
1672
                double y1 = 0;
1673
                double x2 = 0;
1674
                double y2 = 0;
1675
                if (!bForGraphic)
1676
                {
1677
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1678
                    range = new double[] { x1, y1, x2, y2 };
1679
                }
1680
                else
1681
                {
1682
                    x1 = double.MaxValue;
1683
                    y1 = double.MaxValue;
1684
                    x2 = double.MinValue;
1685
                    y2 = double.MinValue;
1686
                    range = new double[] { x1, y1, x2, y2 };
1687

    
1688
                    foreach (var item in symbol2d.DrawingObjects)
1689
                    {
1690
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1691
                        {
1692
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1693
                            if (rangeObject.Layer == "Default")
1694
                            {
1695
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1696
                                range = new double[] {
1697
                                Math.Min(x1, range[0]),
1698
                                Math.Min(y1, range[1]),
1699
                                Math.Max(x2, range[2]),
1700
                                Math.Max(y2, range[3])
1701
                            };
1702
                            }
1703
                        }
1704
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1705
                        {
1706
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1707
                            if (rangeObject.Layer == "Default")
1708
                            {
1709
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1710
                                range = new double[] {
1711
                                Math.Min(x1, range[0]),
1712
                                Math.Min(y1, range[1]),
1713
                                Math.Max(x2, range[2]),
1714
                                Math.Max(y2, range[3])
1715
                            };
1716
                            }
1717
                        }
1718
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1719
                        {
1720
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1721
                            if (rangeObject.Layer == "Default")
1722
                            {
1723
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1724
                                range = new double[] {
1725
                                Math.Min(x1, range[0]),
1726
                                Math.Min(y1, range[1]),
1727
                                Math.Max(x2, range[2]),
1728
                                Math.Max(y2, range[3])
1729
                            };
1730
                            }
1731
                        }
1732
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1733
                        {
1734
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1735
                            if (rangeObject.Layer == "Default")
1736
                            {
1737
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1738
                                range = new double[] {
1739
                                Math.Min(x1, range[0]),
1740
                                Math.Min(y1, range[1]),
1741
                                Math.Max(x2, range[2]),
1742
                                Math.Max(y2, range[3])
1743
                            };
1744
                            }
1745
                        }
1746
                    }
1747
                }
1748

    
1749
                if (!bOnlySymbol)
1750
                {
1751
                    foreach (var childSymbol in symbol.ChildSymbols)
1752
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1753
                }
1754
                ReleaseCOMObjects(_TargetItem);
1755
            }
1756
        }
1757

    
1758
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1759
        {
1760
            if (labelPersist != null)
1761
            {
1762
                double x1 = double.MaxValue;
1763
                double y1 = double.MaxValue;
1764
                double x2 = double.MinValue;
1765
                double y2 = double.MinValue;
1766
                range = new double[] { x1, y1, x2, y2 };
1767

    
1768
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1769
                foreach (var item in dependency.DrawingObjects)
1770
                {
1771
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1772
                    if (textBox != null)
1773
                    {
1774
                        if (dependency != null)
1775
                        {
1776
                            double tempX1;
1777
                            double tempY1;
1778
                            double tempX2;
1779
                            double tempY2;
1780
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1781
                            x1 = Math.Min(x1, tempX1);
1782
                            y1 = Math.Min(y1, tempY1);
1783
                            x2 = Math.Max(x2, tempX2);
1784
                            y2 = Math.Max(y2, tempY2);
1785

    
1786
                            range = new double[] { x1, y1, x2, y2 };
1787
                        }
1788
                    }
1789
                }
1790

    
1791
            }
1792
        }
1793

    
1794
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1795
        {
1796
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1797
            foreach (var symbol in symbols)
1798
            {
1799
                double[] symbolRange = null;
1800
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
1801

    
1802
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
1803
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
1804
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
1805
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
1806

    
1807
                foreach (var childSymbol in symbol.ChildSymbols)
1808
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1809
            }
1810

    
1811
            range = tempRange;
1812
        }
1813

    
1814
        /// <summary>
1815
        /// Child Modeling 된 Symbol의 Range를 구한다.
1816
        /// </summary>
1817
        /// <param name="childSymbol"></param>
1818
        /// <param name="range"></param>
1819
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1820
        {
1821
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1822
            if (_ChildSymbol != null)
1823
            {
1824
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1825
                double x1 = 0;
1826
                double y1 = 0;
1827
                double x2 = 0;
1828
                double y2 = 0;
1829
                symbol2d.Range(out x1, out y1, out x2, out y2);
1830
                range[0] = Math.Min(range[0], x1);
1831
                range[1] = Math.Min(range[1], y1);
1832
                range[2] = Math.Max(range[2], x2);
1833
                range[3] = Math.Max(range[3], y2);
1834

    
1835
                for (int i = 1; i < int.MaxValue; i++)
1836
                {
1837
                    double connX = 0;
1838
                    double connY = 0;
1839
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1840
                        points.Add(new double[] { connX, connY });
1841
                    else
1842
                        break;
1843
                }
1844

    
1845
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1846
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1847

    
1848
                ReleaseCOMObjects(_ChildSymbol);
1849
            }
1850
        }
1851

    
1852
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1853
        {
1854
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1855
            if (_ChildSymbol != null)
1856
            {
1857
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1858
                double x1 = 0;
1859
                double y1 = 0;
1860
                double x2 = 0;
1861
                double y2 = 0;
1862
                symbol2d.Range(out x1, out y1, out x2, out y2);
1863
                range[0] = Math.Min(range[0], x1);
1864
                range[1] = Math.Min(range[1], y1);
1865
                range[2] = Math.Max(range[2], x2);
1866
                range[3] = Math.Max(range[3], y2);
1867

    
1868
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1869
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1870
                ReleaseCOMObjects(_ChildSymbol);
1871
            }
1872
        }
1873

    
1874
        /// <summary>
1875
        /// Label Symbol Modeling
1876
        /// </summary>
1877
        /// <param name="symbol"></param>
1878
        private void LabelSymbolModeling(Symbol symbol)
1879
        {
1880
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1881
            {
1882
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1883
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1884
                    return;
1885
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1886

    
1887
                string symbolUID = itemAttribute.VALUE;
1888
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1889
                if (targetItem != null &&
1890
                    (targetItem.GetType() == typeof(Symbol) ||
1891
                    targetItem.GetType() == typeof(Equipment)))
1892
                {
1893
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1894
                    string sRep = null;
1895
                    if (targetItem.GetType() == typeof(Symbol))
1896
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1897
                    else if (targetItem.GetType() == typeof(Equipment))
1898
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1899
                    if (!string.IsNullOrEmpty(sRep))
1900
                    {
1901
                        // LEADER Line 검사
1902
                        bool leaderLine = false;
1903
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1904
                        if (symbolMapping != null)
1905
                            leaderLine = symbolMapping.LEADERLINE;
1906

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

    
1911
                        //Leader 선 센터로
1912
                        if (_LMLabelPresist != null)
1913
                        {
1914
                            // Target Item에 Label의 Attribute Input
1915
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1916

    
1917
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1918
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1919
                            if (dependency != null)
1920
                            {
1921
                                bool result = false;
1922
                                foreach (var attributes in dependency.AttributeSets)
1923
                                {
1924
                                    foreach (var attribute in attributes)
1925
                                    {
1926
                                        string name = attribute.Name;
1927
                                        string value = attribute.GetValue().ToString();
1928
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1929
                                        {
1930
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1931
                                            {
1932
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1933
                                                {
1934
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1935
                                                    double prevX = _TargetItem.get_XCoordinate();
1936
                                                    double prevY = _TargetItem.get_YCoordinate();
1937
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1938
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1939
                                                    result = true;
1940
                                                    break;
1941
                                                }
1942
                                            }
1943
                                        }
1944

    
1945
                                        if (result)
1946
                                            break;
1947
                                    }
1948

    
1949
                                    if (result)
1950
                                        break;
1951
                                }
1952
                            }
1953

    
1954
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1955
                            _LMLabelPresist.Commit();
1956
                            ReleaseCOMObjects(_LMLabelPresist);
1957
                        }
1958

    
1959
                        ReleaseCOMObjects(_TargetItem);
1960
                    }
1961
                }
1962
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1963
                {
1964
                    Line targetLine = targetItem as Line;
1965
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1966
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1967
                    if (connectedLMConnector != null)
1968
                    {
1969
                        // Target Item에 Label의 Attribute Input
1970
                        InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1971

    
1972
                        // LEADER Line 검사
1973
                        bool leaderLine = false;
1974
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1975
                        if (symbolMapping != null)
1976
                            leaderLine = symbolMapping.LEADERLINE;
1977

    
1978
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: symbol.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1979
                        if (_LMLabelPresist != null)
1980
                        {
1981
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1982
                            _LMLabelPresist.Commit();
1983
                            ReleaseCOMObjects(_LMLabelPresist);
1984
                        }
1985
                        ReleaseCOMObjects(connectedLMConnector);
1986
                    }
1987

    
1988
                    foreach (var item in connectorVertices)
1989
                        if (item.Key != null)
1990
                            ReleaseCOMObjects(item.Key);
1991
                }
1992
            }
1993
        }
1994

    
1995
        /// <summary>
1996
        /// Equipment를 실제로 Modeling 메서드
1997
        /// </summary>
1998
        /// <param name="equipment"></param>
1999
        private void EquipmentModeling(Equipment equipment)
2000
        {
2001
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
2002
                return;
2003

    
2004
            LMSymbol _LMSymbol = null;
2005
            LMSymbol targetItem = null;
2006
            string mappingPath = equipment.SPPID.MAPPINGNAME;
2007
            double x = equipment.SPPID.ORIGINAL_X;
2008
            double y = equipment.SPPID.ORIGINAL_Y;
2009
            int mirror = 0;
2010
            double angle = equipment.ANGLE;
2011

    
2012
            // Mirror 계산
2013
            if (equipment.FLIP == 1)
2014
            {
2015
                mirror = 1;
2016
                if (angle == Math.PI || angle == 0)
2017
                    angle += Math.PI;
2018
            }
2019

    
2020
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
2021

    
2022
            Connector connector = equipment.CONNECTORS.Find(conn =>
2023
            !string.IsNullOrEmpty(conn.CONNECTEDITEM) &&
2024
            conn.CONNECTEDITEM != "None" &&
2025
            conn.ConnectedObject.GetType() == typeof(Equipment));
2026

    
2027
            if (connector != null)
2028
            {
2029
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
2030
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
2031
                if (connEquipment != null)
2032
                {
2033
                    //if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2034
                    //    EquipmentModeling(connEquipment);
2035

    
2036
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2037
                    {
2038
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
2039
                        if (targetItem != null)
2040
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2041
                        else
2042
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2043
                    }
2044
                    else
2045
                    {
2046
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2047
                    }
2048
                }
2049
                else if (connVendorPackage != null)
2050
                {
2051
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
2052
                    {
2053
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
2054
                        if (targetItem != null)
2055
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2056
                        else
2057
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2058
                    }
2059
                }
2060
                else
2061
                {
2062
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2063
                }
2064
            }
2065
            else
2066
            {
2067
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2068
            }
2069

    
2070
            if (_LMSymbol != null)
2071
            {
2072
                _LMSymbol.Commit();
2073
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2074
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
2075
                ReleaseCOMObjects(_LMSymbol);
2076
            }
2077

    
2078
            if (targetItem != null)
2079
            {
2080
                ReleaseCOMObjects(targetItem);
2081
            }
2082

    
2083
            ReleaseCOMObjects(_LMSymbol);
2084
        }
2085

    
2086
        private void VendorPackageModeling(VendorPackage vendorPackage)
2087
        {
2088
            ETCSetting setting = ETCSetting.GetInstance();
2089
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2090
            {
2091
                string symbolPath = setting.VendorPackageSymbolPath;
2092
                double x = vendorPackage.SPPID.ORIGINAL_X;
2093
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2094

    
2095
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2096
                if (symbol != null)
2097
                {
2098
                    symbol.Commit();
2099
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2100
                }
2101

    
2102
                ReleaseCOMObjects(symbol);
2103
                symbol = null;
2104
            }
2105
        }
2106

    
2107
        /// <summary>
2108
        /// 첫 진입점
2109
        /// </summary>
2110
        /// <param name="symbol"></param>
2111
        private void SymbolModelingBySymbol(Symbol symbol)
2112
        {
2113
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2114
            List<object> endObjects = new List<object>();
2115
            endObjects.Add(symbol);
2116

    
2117
            /// 심볼에 연결되어 있는 항목들을 모델링한다
2118
            foreach (var connector in symbol.CONNECTORS)
2119
            {
2120
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2121
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2122
                {
2123
                    endObjects.Add(connItem);
2124
                    if (connItem.GetType() == typeof(Symbol))
2125
                    {
2126
                        Symbol connSymbol = connItem as Symbol;
2127
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2128
                        {
2129
                            SymbolModeling(connSymbol, symbol);
2130
                        }
2131
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2132
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2133
                    }
2134
                    else if (connItem.GetType() == typeof(Line))
2135
                    {
2136
                        Line connLine = connItem as Line;
2137
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2138
                    }
2139
                }
2140
            }
2141
        }
2142

    
2143
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2144
        {
2145
            foreach (var connector in symbol.CONNECTORS)
2146
            {
2147
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2148
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2149
                {
2150
                    if (!endObjects.Contains(connItem))
2151
                    {
2152
                        endObjects.Add(connItem);
2153
                        if (connItem.GetType() == typeof(Symbol))
2154
                        {
2155
                            Symbol connSymbol = connItem as Symbol;
2156
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2157
                            {
2158
                                SymbolModeling(connSymbol, symbol);
2159
                            }
2160
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2161
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2162
                        }
2163
                        else if (connItem.GetType() == typeof(Line))
2164
                        {
2165
                            Line connLine = connItem as Line;
2166
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2167
                        }
2168
                    }
2169
                }
2170
            }
2171
        }
2172

    
2173
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2174
        {
2175
            foreach (var connector in line.CONNECTORS)
2176
            {
2177
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2178
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2179
                {
2180
                    if (!endObjects.Contains(connItem))
2181
                    {
2182
                        endObjects.Add(connItem);
2183
                        if (connItem.GetType() == typeof(Symbol))
2184
                        {
2185
                            Symbol connSymbol = connItem as Symbol;
2186
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2187
                            {
2188
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2189
                                int branchCount = 0;
2190
                                if (connLine != null)
2191
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2192

    
2193
                                List<Symbol> group = new List<Symbol>();
2194
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2195
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2196
                                List<Symbol> endModelingGroup = new List<Symbol>();
2197
                                if (priority != null)
2198
                                {
2199
                                    SymbolGroupModeling(priority, group);
2200

    
2201
                                    // Range 겹치는지 확인해야함
2202
                                    double[] prevRange = null;
2203
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2204
                                    double[] groupRange = null;
2205
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2206

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

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

    
2240
                                                SymbolGroupModeling(priority, group);
2241
                                            }
2242
                                        }
2243
                                    }
2244
                                }
2245
                                else
2246
                                {
2247
                                    SymbolModeling(connSymbol, null);
2248
                                    // Range 겹치는지 확인해야함
2249
                                    double[] prevRange = null;
2250
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2251
                                    double[] connRange = null;
2252
                                    GetSPPIDSymbolRange(connSymbol, ref connRange, bForGraphic: true);
2253

    
2254
                                    double distanceX = 0;
2255
                                    double distanceY = 0;
2256
                                    bool overlapX = false;
2257
                                    bool overlapY = false;
2258
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2259
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2260
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2261
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2262
                                    {
2263
                                        RemoveSymbol(connSymbol);
2264
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2265

    
2266
                                        SymbolModeling(connSymbol, null);
2267
                                    }
2268
                                    else if (branchCount > 0)
2269
                                    {
2270
                                        LMConnector _connector = JustLineModeling(connLine);
2271
                                        if (_connector != null)
2272
                                        {
2273
                                            double distance = GetConnectorDistance(_connector);
2274
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2275
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2276
                                            _connector.Commit();
2277
                                            ReleaseCOMObjects(_connector);
2278
                                            _connector = null;
2279
                                            if (cellCount < branchCount + 1)
2280
                                            {
2281
                                                int moveCount = branchCount - cellCount;
2282
                                                RemoveSymbol(group);
2283
                                                foreach (var _temp in group)
2284
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2285

    
2286
                                                SymbolGroupModeling(priority, group);
2287
                                            }
2288
                                        }
2289
                                    }
2290
                                }
2291
                            }
2292
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2293
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2294
                        }
2295
                        else if (connItem.GetType() == typeof(Line))
2296
                        {
2297
                            Line connLine = connItem as Line;
2298
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2299
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2300
                        }
2301
                    }
2302
                }
2303
            }
2304
        }
2305

    
2306
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2307
        {
2308
            List<Symbol> endModelingGroup = new List<Symbol>();
2309
            SymbolModeling(firstSymbol, null);
2310
            endModelingGroup.Add(firstSymbol);
2311
            while (endModelingGroup.Count != group.Count)
2312
            {
2313
                foreach (var _symbol in group)
2314
                {
2315
                    if (!endModelingGroup.Contains(_symbol))
2316
                    {
2317
                        foreach (var _connector in _symbol.CONNECTORS)
2318
                        {
2319
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2320
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2321
                            {
2322
                                SymbolModeling(_symbol, _connSymbol);
2323
                                endModelingGroup.Add(_symbol);
2324
                                break;
2325
                            }
2326
                        }
2327
                    }
2328
                }
2329
            }
2330
        }
2331

    
2332
        /// <summary>
2333
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2334
        /// </summary>
2335
        /// <param name="childSymbol"></param>
2336
        /// <param name="parentSymbol"></param>
2337
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2338
        {
2339
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2340
            double x1 = 0;
2341
            double x2 = 0;
2342
            double y1 = 0;
2343
            double y2 = 0;
2344
            symbol2d.Range(out x1, out y1, out x2, out y2);
2345

    
2346
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2347
            if (_LMSymbol != null)
2348
            {
2349
                _LMSymbol.Commit();
2350
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2351
                foreach (var item in childSymbol.ChildSymbols)
2352
                    CreateChildSymbol(item, _LMSymbol, parent);
2353
            }
2354

    
2355

    
2356
            ReleaseCOMObjects(_LMSymbol);
2357
        }
2358
        double index = 0;
2359
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2360
        {
2361
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2362
                return;
2363

    
2364
            List<Line> group = new List<Line>();
2365
            GetConnectedLineGroup(line, group);
2366
            LineCoordinateCorrection(group);
2367

    
2368
            foreach (var groupLine in group)
2369
            {
2370
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2371
                {
2372
                    BranchLines.Add(groupLine);
2373
                    continue;
2374
                }
2375

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

    
2447
                            placeRunInputs.AddPoint(x, y);
2448

    
2449
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2450
                            {
2451
                                index += 0.01;
2452
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2453
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2454
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2455
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2456
                                else
2457
                                {
2458
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2459
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2460
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2461
                                    else
2462
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2463
                                }
2464
                            }
2465
                        }
2466
                    }
2467
                    else
2468
                        placeRunInputs.AddPoint(x, y);
2469
                }
2470

    
2471
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2472
                if (_lMConnector != null)
2473
                {
2474
                    _lMConnector.Commit();
2475
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2476

    
2477
                    bool bRemodelingStart = false;
2478
                    if (_LMSymbolStart != null)
2479
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2480
                    bool bRemodelingEnd = false;
2481
                    if (_LMSymbolEnd != null)
2482
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2483

    
2484
                    if (bRemodelingStart || bRemodelingEnd)
2485
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2486

    
2487
                    FlowMarkModeling(groupLine);
2488

    
2489
                    ReleaseCOMObjects(_lMConnector);
2490

    
2491
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2492
                    if (modelItem != null)
2493
                    {
2494
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2495
                        if (attribute != null)
2496
                            attribute.set_Value("End 1 is upstream (Inlet)");
2497
                        modelItem.Commit();
2498
                    }
2499
                    ReleaseCOMObjects(modelItem);
2500
                    modelItem = null;
2501
                }
2502
                else if (!isBranchModeling)
2503
                {
2504
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2505
                }
2506

    
2507
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2508
                x.ConnectedObject != null &&
2509
                x.ConnectedObject.GetType() == typeof(Line) &&
2510
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2511
                .Select(x => x.ConnectedObject)
2512
                .ToList();
2513

    
2514
                foreach (var item in removeLines)
2515
                    RemoveLineForModeling(item as Line);
2516

    
2517
                ReleaseCOMObjects(_LMAItem);
2518
                _LMAItem = null;
2519
                ReleaseCOMObjects(placeRunInputs);
2520
                placeRunInputs = null;
2521
                ReleaseCOMObjects(_LMSymbolStart);
2522
                _LMSymbolStart = null;
2523
                ReleaseCOMObjects(_LMSymbolEnd);
2524
                _LMSymbolEnd = null;
2525

    
2526
                if (isBranchModeling && BranchLines.Contains(groupLine))
2527
                    BranchLines.Remove(groupLine);
2528
            }
2529
        }
2530

    
2531
        private LMConnector JustLineModeling(Line line)
2532
        {
2533
            bool diagonal = false;
2534
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2535
                diagonal = true;
2536
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2537
            LMSymbol _LMSymbolStart = null;
2538
            LMSymbol _LMSymbolEnd = null;
2539
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2540
            foreach (var connector in line.CONNECTORS)
2541
            {
2542
                double x = 0;
2543
                double y = 0;
2544
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2545
                if (connector.ConnectedObject == null)
2546
                {
2547
                    placeRunInputs.AddPoint(x, y);
2548
                }
2549
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2550
                {
2551
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2552
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2553
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2554
                    {
2555
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2556
                        if (_LMSymbolStart != null)
2557
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2558
                        else
2559
                            placeRunInputs.AddPoint(x, y);
2560
                    }
2561
                    else
2562
                    {
2563
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2564
                        if (_LMSymbolEnd != null)
2565
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2566
                        else
2567
                            placeRunInputs.AddPoint(x, y);
2568
                    }
2569
                }
2570
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2571
                {
2572
                    Line targetLine = connector.ConnectedObject as Line;
2573
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2574
                    {
2575
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2576
                        if (targetConnector != null)
2577
                        {
2578
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2579
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2580
                        }
2581
                        else
2582
                        {
2583
                            placeRunInputs.AddPoint(x, y);
2584
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2585
                        }
2586
                    }
2587
                    else
2588
                        placeRunInputs.AddPoint(x, y);
2589
                }
2590
            }
2591

    
2592
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2593
            if (_lMConnector != null)
2594
                _lMConnector.Commit();
2595

    
2596
            ReleaseCOMObjects(_LMAItem);
2597
            _LMAItem = null;
2598
            ReleaseCOMObjects(placeRunInputs);
2599
            placeRunInputs = null;
2600
            ReleaseCOMObjects(_LMSymbolStart);
2601
            _LMSymbolStart = null;
2602
            ReleaseCOMObjects(_LMSymbolEnd);
2603
            _LMSymbolEnd = null;
2604

    
2605
            return _lMConnector;
2606
        }
2607

    
2608
        private void RemoveLineForModeling(Line line)
2609
        {
2610
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2611
            if (modelItem != null)
2612
            {
2613
                foreach (LMRepresentation rep in modelItem.Representations)
2614
                {
2615
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2616
                    {
2617
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2618
                        dynamic OID = rep.get_GraphicOID().ToString();
2619
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2620
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2621
                        int verticesCount = lineStringGeometry.VertexCount;
2622
                        double[] vertices = null;
2623
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2624
                        for (int i = 0; i < verticesCount; i++)
2625
                        {
2626
                            double x = 0;
2627
                            double y = 0;
2628
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2629
                            if (verticesCount == 2 && (x < 0 || y < 0))
2630
                                _placement.PIDRemovePlacement(rep);
2631
                        }
2632
                        ReleaseCOMObjects(_LMConnector);
2633
                    }
2634
                }
2635

    
2636
                ReleaseCOMObjects(modelItem);
2637
            }
2638
        }
2639

    
2640
        private void RemoveLine(Line line)
2641
        {
2642
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2643
            if (modelItem != null)
2644
            {
2645
                foreach (LMRepresentation rep in modelItem.Representations)
2646
                {
2647
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2648
                        _placement.PIDRemovePlacement(rep);
2649
                }
2650
                ReleaseCOMObjects(modelItem);
2651
            }
2652
            line.SPPID.ModelItemId = null;
2653
        }
2654

    
2655
        private void GetConnectedLineGroup(Line line, List<Line> group)
2656
        {
2657
            if (!group.Contains(line))
2658
                group.Add(line);
2659
            foreach (var connector in line.CONNECTORS)
2660
            {
2661
                if (connector.ConnectedObject != null &&
2662
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2663
                    !group.Contains(connector.ConnectedObject) &&
2664
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2665
                {
2666
                    Line connLine = connector.ConnectedObject as Line;
2667
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2668
                    {
2669
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2670
                            group.Insert(0, connLine);
2671
                        else
2672
                            group.Add(connLine);
2673
                        GetConnectedLineGroup(connLine, group);
2674
                    }
2675
                }
2676
            }
2677
        }
2678

    
2679
        private void LineCoordinateCorrection(List<Line> group)
2680
        {
2681
            // 순서대로 전 Item 기준 정렬
2682
            LineCoordinateCorrectionByStart(group);
2683

    
2684
            // 역으로 심볼이 있을 경우 좌표 보정
2685
            LineCoordinateCorrectionForLastLine(group);
2686
        }
2687

    
2688
        private void LineCoordinateCorrectionByStart(List<Line> group)
2689
        {
2690
            for (int i = 0; i < group.Count; i++)
2691
            {
2692
                Line line = group[i];
2693
                if (i == 0)
2694
                {
2695
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2696
                    if (symbolConnector != null)
2697
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2698
                }
2699
                else if (i != 0)
2700
                {
2701
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2702
                }
2703
            }
2704
        }
2705

    
2706
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2707
        {
2708
            Line checkLine = group[group.Count - 1];
2709
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2710
            if (lastSymbolConnector != null)
2711
            {
2712
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2713
                for (int i = group.Count - 2; i >= 0; i--)
2714
                {
2715
                    Line line = group[i + 1];
2716
                    Line prevLine = group[i];
2717

    
2718
                    // 같으면 보정
2719
                    if (line.SlopeType == prevLine.SlopeType)
2720
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2721
                    else
2722
                    {
2723
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2724
                        {
2725
                            double prevX = 0;
2726
                            double prevY = 0;
2727
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2728
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2729

    
2730
                            double x = 0;
2731
                            double y = 0;
2732
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2733
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2734
                        }
2735
                        else if (line.SlopeType == SlopeType.VERTICAL)
2736
                        {
2737
                            double prevX = 0;
2738
                            double prevY = 0;
2739
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2740
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2741

    
2742
                            double x = 0;
2743
                            double y = 0;
2744
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2745
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2746
                        }
2747
                        break;
2748
                    }
2749
                }
2750
            }
2751
        }
2752

    
2753
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2754
        {
2755
            double x = 0;
2756
            double y = 0;
2757
            if (connItem.GetType() == typeof(Symbol))
2758
            {
2759
                Symbol targetSymbol = connItem as Symbol;
2760
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2761
                if (targetConnector != null)
2762
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2763
                else
2764
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2765
            }
2766
            else if (connItem.GetType() == typeof(Line))
2767
            {
2768
                Line targetLine = connItem as Line;
2769
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2770
            }
2771

    
2772
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2773
        }
2774

    
2775
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2776
        {
2777
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2778
            int index = line.CONNECTORS.IndexOf(connector);
2779
            if (index == 0)
2780
            {
2781
                line.SPPID.START_X = x;
2782
                line.SPPID.START_Y = y;
2783
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2784
                    line.SPPID.END_Y = y;
2785
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2786
                    line.SPPID.END_X = x;
2787
            }
2788
            else
2789
            {
2790
                line.SPPID.END_X = x;
2791
                line.SPPID.END_Y = y;
2792
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2793
                    line.SPPID.START_Y = y;
2794
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2795
                    line.SPPID.START_X = x;
2796
            }
2797
        }
2798

    
2799
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2800
        {
2801
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2802
            int index = line.CONNECTORS.IndexOf(connector);
2803
            if (index == 0)
2804
            {
2805
                line.SPPID.START_X = x;
2806
                if (line.SlopeType == SlopeType.VERTICAL)
2807
                    line.SPPID.END_X = x;
2808
            }
2809
            else
2810
            {
2811
                line.SPPID.END_X = x;
2812
                if (line.SlopeType == SlopeType.VERTICAL)
2813
                    line.SPPID.START_X = x;
2814
            }
2815
        }
2816

    
2817
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2818
        {
2819
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2820
            int index = line.CONNECTORS.IndexOf(connector);
2821
            if (index == 0)
2822
            {
2823
                line.SPPID.START_Y = y;
2824
                if (line.SlopeType == SlopeType.HORIZONTAL)
2825
                    line.SPPID.END_Y = y;
2826
            }
2827
            else
2828
            {
2829
                line.SPPID.END_Y = y;
2830
                if (line.SlopeType == SlopeType.HORIZONTAL)
2831
                    line.SPPID.START_Y = y;
2832
            }
2833
        }
2834

    
2835
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2836
        {
2837
            if (symbol != null)
2838
            {
2839
                string repID = symbol.AsLMRepresentation().Id;
2840
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2841
                string lineUID = line.UID;
2842

    
2843
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2844
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2845
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2846

    
2847
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2848
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2849
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2850

    
2851
                if (startSpecBreak != null || startEndBreak != null)
2852
                    result = true;
2853
            }
2854
        }
2855

    
2856
        /// <summary>
2857
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2858
        /// </summary>
2859
        /// <param name="lines"></param>
2860
        /// <param name="prevLMConnector"></param>
2861
        /// <param name="startSymbol"></param>
2862
        /// <param name="endSymbol"></param>
2863
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2864
        {
2865
            string symbolPath = string.Empty;
2866
            #region get symbol path
2867
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2868
            symbolPath = GetSPPIDFileName(modelItem);
2869
            ReleaseCOMObjects(modelItem);
2870
            #endregion
2871
            bool diagonal = false;
2872
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2873
                diagonal = true;
2874
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2875
            LMConnector newConnector = null;
2876
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2877
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2878
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2879
            int verticesCount = lineStringGeometry.VertexCount;
2880
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2881

    
2882
            List<double[]> vertices = new List<double[]>();
2883
            for (int i = 1; i <= verticesCount; i++)
2884
            {
2885
                double x = 0;
2886
                double y = 0;
2887
                lineStringGeometry.GetVertex(i, ref x, ref y);
2888
                vertices.Add(new double[] { x, y });
2889
            }
2890

    
2891
            for (int i = 0; i < vertices.Count; i++)
2892
            {
2893
                double[] points = vertices[i];
2894
                // 시작 심볼이 있고 첫번째 좌표일 때
2895
                if (startSymbol != null && i == 0)
2896
                {
2897
                    if (bStart)
2898
                    {
2899
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2900
                        if (slopeType == SlopeType.HORIZONTAL)
2901
                            placeRunInputs.AddPoint(points[0], -0.1);
2902
                        else if (slopeType == SlopeType.VERTICAL)
2903
                            placeRunInputs.AddPoint(-0.1, points[1]);
2904
                        else
2905
                            placeRunInputs.AddPoint(points[0], -0.1);
2906

    
2907
                        placeRunInputs.AddPoint(points[0], points[1]);
2908
                    }
2909
                    else
2910
                    {
2911
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2912
                    }
2913
                }
2914
                // 마지막 심볼이 있고 마지막 좌표일 때
2915
                else if (endSymbol != null && i == vertices.Count - 1)
2916
                {
2917
                    if (bEnd)
2918
                    {
2919
                        placeRunInputs.AddPoint(points[0], points[1]);
2920

    
2921
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2922
                        if (slopeType == SlopeType.HORIZONTAL)
2923
                            placeRunInputs.AddPoint(points[0], -0.1);
2924
                        else if (slopeType == SlopeType.VERTICAL)
2925
                            placeRunInputs.AddPoint(-0.1, points[1]);
2926
                        else
2927
                            placeRunInputs.AddPoint(points[0], -0.1);
2928
                    }
2929
                    else
2930
                    {
2931
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2932
                    }
2933
                }
2934
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2935
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2936
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2937
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2938
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2939
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2940
                else
2941
                    placeRunInputs.AddPoint(points[0], points[1]);
2942
            }
2943

    
2944
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2945
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2946

    
2947
            ReleaseCOMObjects(placeRunInputs);
2948
            ReleaseCOMObjects(_LMAItem);
2949
            ReleaseCOMObjects(modelItem);
2950

    
2951
            if (newConnector != null)
2952
            {
2953
                newConnector.Commit();
2954
                if (startSymbol != null && bStart)
2955
                {
2956
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2957
                    placeRunInputs = new PlaceRunInputs();
2958
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2959
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2960
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2961
                    if (_LMConnector != null)
2962
                    {
2963
                        _LMConnector.Commit();
2964
                        RemoveConnectorForReModelingLine(newConnector);
2965
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2966
                        ReleaseCOMObjects(_LMConnector);
2967
                    }
2968
                    ReleaseCOMObjects(placeRunInputs);
2969
                    ReleaseCOMObjects(_LMAItem);
2970
                }
2971

    
2972
                if (endSymbol != null && bEnd)
2973
                {
2974
                    if (startSymbol != null)
2975
                    {
2976
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2977
                        newConnector = dicVertices.First().Key;
2978
                    }
2979

    
2980
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2981
                    placeRunInputs = new PlaceRunInputs();
2982
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2983
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2984
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2985
                    if (_LMConnector != null)
2986
                    {
2987
                        _LMConnector.Commit();
2988
                        RemoveConnectorForReModelingLine(newConnector);
2989
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2990
                        ReleaseCOMObjects(_LMConnector);
2991
                    }
2992
                    ReleaseCOMObjects(placeRunInputs);
2993
                    ReleaseCOMObjects(_LMAItem);
2994
                }
2995

    
2996
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2997
                ReleaseCOMObjects(newConnector);
2998
            }
2999

    
3000
            ReleaseCOMObjects(modelItem);
3001
        }
3002

    
3003
        /// <summary>
3004
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
3005
        /// </summary>
3006
        /// <param name="connector"></param>
3007
        private void RemoveConnectorForReModelingLine(LMConnector connector)
3008
        {
3009
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
3010
            foreach (var item in dicVertices)
3011
            {
3012
                if (item.Value.Count == 2)
3013
                {
3014
                    bool result = false;
3015
                    foreach (var point in item.Value)
3016
                    {
3017
                        if (point[0] < 0 || point[1] < 0)
3018
                        {
3019
                            result = true;
3020
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
3021
                            break;
3022
                        }
3023
                    }
3024

    
3025
                    if (result)
3026
                        break;
3027
                }
3028
            }
3029
            foreach (var item in dicVertices)
3030
                ReleaseCOMObjects(item.Key);
3031
        }
3032

    
3033
        /// <summary>
3034
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
3035
        /// </summary>
3036
        /// <param name="symbol"></param>
3037
        /// <param name="line"></param>
3038
        /// <returns></returns>
3039
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
3040
        {
3041
            LMSymbol _LMSymbol = null;
3042
            foreach (var connector in symbol.CONNECTORS)
3043
            {
3044
                if (connector.CONNECTEDITEM == line.UID)
3045
                {
3046
                    if (connector.Index == 0)
3047
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3048
                    else
3049
                    {
3050
                        ChildSymbol child = null;
3051
                        foreach (var childSymbol in symbol.ChildSymbols)
3052
                        {
3053
                            if (childSymbol.Connectors.Contains(connector))
3054
                                child = childSymbol;
3055
                            else
3056
                                child = GetChildSymbolByConnector(childSymbol, connector);
3057

    
3058
                            if (child != null)
3059
                                break;
3060
                        }
3061

    
3062
                        if (child != null)
3063
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3064
                    }
3065

    
3066
                    break;
3067
                }
3068
            }
3069

    
3070
            return _LMSymbol;
3071
        }
3072

    
3073
        /// <summary>
3074
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3075
        /// </summary>
3076
        /// <param name="item"></param>
3077
        /// <param name="connector"></param>
3078
        /// <returns></returns>
3079
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3080
        {
3081
            foreach (var childSymbol in item.ChildSymbols)
3082
            {
3083
                if (childSymbol.Connectors.Contains(connector))
3084
                    return childSymbol;
3085
                else
3086
                    return GetChildSymbolByConnector(childSymbol, connector);
3087
            }
3088

    
3089
            return null;
3090
        }
3091

    
3092
        /// <summary>
3093
        /// EndBreak 모델링 메서드
3094
        /// </summary>
3095
        /// <param name="endBreak"></param>
3096
        private void EndBreakModeling(EndBreak endBreak)
3097
        {
3098
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3099
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3100

    
3101
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3102
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3103
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3104

    
3105
            if (targetLMConnector != null)
3106
            {
3107
                // LEADER Line 검사
3108
                bool leaderLine = false;
3109
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3110
                if (symbolMapping != null)
3111
                    leaderLine = symbolMapping.LEADERLINE;
3112

    
3113
                SegmentLocation location;
3114
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3115
                Array array = null;
3116
                if (point != null)
3117
                    array = new double[] { 0, point[0], point[1] };
3118
                else
3119
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3120

    
3121
                LMLabelPersist _LmLabelPersist;
3122

    
3123
                Property property = endBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Freeze");
3124
                if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3125
                {
3126
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3127
                }
3128
                else
3129
                {
3130
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3131
                }
3132
                
3133
                if (_LmLabelPersist != null)
3134
                {
3135
                    _LmLabelPersist.Commit();
3136
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3137
                    if (_LmLabelPersist.ModelItemObject != null)
3138
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3139
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3140

    
3141
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3142

    
3143
                    // end break arrange
3144
                    if (property == null || string.IsNullOrEmpty(property.VALUE) || !property.VALUE.Equals("True"))
3145
                    {
3146
                        MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3147
                    }
3148

    
3149
                    ReleaseCOMObjects(_LmLabelPersist);
3150
                }
3151
                ReleaseCOMObjects(targetLMConnector);
3152
            }
3153
            else
3154
            {
3155
                Log.Write("End Break UID : " + endBreak.UID);
3156
                Log.Write("Can't find targetLMConnector");
3157
            }
3158
        }
3159

    
3160
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3161
        {
3162
            double x = 0, y = 0;
3163
            if (location.HasFlag(SegmentLocation.Up))
3164
                y = GridSetting.GetInstance().Length * 3;
3165
            else if (location.HasFlag(SegmentLocation.Down))
3166
                y = -GridSetting.GetInstance().Length * 3;
3167

    
3168
            if (location.HasFlag(SegmentLocation.Right))
3169
                x = GridSetting.GetInstance().Length * 3;
3170
            else if (location.HasFlag(SegmentLocation.Left))
3171
                x = -GridSetting.GetInstance().Length * 3;
3172

    
3173
            if (x != 0 || y != 0)
3174
            {
3175
                radApp.ActiveSelectSet.RemoveAll();
3176
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3177
                if (dependency != null)
3178
                {
3179
                    radApp.ActiveSelectSet.Add(dependency);
3180
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3181
                    transform.DefineByMove2d(x, y);
3182
                    radApp.ActiveSelectSet.Transform(transform, true);
3183
                    radApp.ActiveSelectSet.RemoveAll();
3184
                }
3185
            }
3186
        }
3187

    
3188
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3189
        {
3190
            string symbolPath = string.Empty;
3191
            #region get symbol path
3192
            if (string.IsNullOrEmpty(changeSymbolPath))
3193
            {
3194
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3195
                symbolPath = GetSPPIDFileName(modelItem);
3196
                ReleaseCOMObjects(modelItem);
3197
            }
3198
            else
3199
                symbolPath = changeSymbolPath;
3200

    
3201
            #endregion
3202

    
3203
            LMConnector newConnector = null;
3204
            dynamic OID = connector.get_GraphicOID().ToString();
3205
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3206
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3207
            int verticesCount = lineStringGeometry.VertexCount;
3208
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3209
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3210

    
3211
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3212
            {
3213
                double[] vertices = null;
3214
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3215
                double x = 0;
3216
                double y = 0;
3217
                lineStringGeometry.GetVertex(1, ref x, ref y);
3218

    
3219
                string flowDirection = string.Empty;
3220
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3221
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3222
                    flowDirection = flowAttribute.get_Value().ToString();
3223

    
3224
                if (flowDirection == "End 1 is downstream (Outlet)")
3225
                {
3226
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3227
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3228
                    flowDirection = "End 1 is upstream (Inlet)";
3229
                }
3230
                else
3231
                {
3232
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3233
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3234
                }
3235
                string oldModelItemId = connector.ModelItemID;
3236
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3237
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3238
                newConnector.Commit();
3239
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3240
                if (!string.IsNullOrEmpty(flowDirection))
3241
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3242
                ReleaseCOMObjects(connector);
3243

    
3244
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3245
                {
3246
                    foreach (var repId in line.SPPID.Representations)
3247
                    {
3248
                        LMConnector _connector = dataSource.GetConnector(repId);
3249
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3250
                        {
3251
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3252
                            {
3253
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3254
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3255
                            }
3256
                        }
3257
                        ReleaseCOMObjects(_connector);
3258
                        _connector = null;
3259
                    }
3260
                }
3261
            }
3262

    
3263
            return newConnector;
3264
        }
3265

    
3266
        /// <summary>
3267
        /// SpecBreak Modeling 메서드
3268
        /// </summary>
3269
        /// <param name="specBreak"></param>
3270
        private void SpecBreakModeling(SpecBreak specBreak)
3271
        {
3272
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3273
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3274

    
3275
            if (upStreamObj != null &&
3276
                downStreamObj != null)
3277
            {
3278
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3279
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) &&
3280
                    targetLMConnector != null &&
3281
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3282
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3283

    
3284
                if (targetLMConnector != null)
3285
                {
3286
                    foreach (var attribute in specBreak.ATTRIBUTES)
3287
                    {
3288
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3289
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3290
                        {
3291
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3292
                            SegmentLocation location;
3293
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3294
                            Array array = null;
3295
                            if (point != null)
3296
                                array = new double[] { 0, point[0], point[1] };
3297
                            else
3298
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3299
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3300

    
3301
                            if (_LmLabelPersist != null)
3302
                            {
3303
                                _LmLabelPersist.Commit();
3304
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3305
                                if (_LmLabelPersist.ModelItemObject != null)
3306
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3307
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3308

    
3309
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3310

    
3311
                                // spec break arrange
3312
                                MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3313

    
3314
                                ReleaseCOMObjects(_LmLabelPersist);
3315
                            }
3316
                        }
3317
                    }
3318

    
3319
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3320
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3321
                    {
3322
                        // temp
3323
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3324
                    }
3325
                    ReleaseCOMObjects(targetLMConnector);
3326
                }
3327
                else
3328
                {
3329
                    Log.Write("Spec Break UID : " + specBreak.UID);
3330
                    Log.Write("Can't find targetLMConnector");
3331
                }
3332
            }
3333
        }
3334

    
3335
        private bool IsRhombus(LMLabelPersist labelPersist, out double x, out double y, out double radius)
3336
        {
3337
            bool result = false;
3338
            x = 0; y = 0; radius = 0;
3339

    
3340
            string oid = labelPersist.get_GraphicOID().ToString();
3341
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3342

    
3343
            if (dependency != null)
3344
            {
3345
                bool isLabel = false;
3346
                foreach (var attributes in dependency.AttributeSets)
3347
                {
3348
                    foreach (var attribute in attributes)
3349
                    {
3350
                        string name = attribute.Name;
3351
                        string value = attribute.GetValue().ToString();
3352
                        if (name == "DrawingItemType" && value == "LabelPersist")
3353
                        {
3354
                            isLabel = true;
3355
                            break;
3356
                        }
3357
                    }
3358
                }
3359
                if (isLabel)
3360
                {
3361
                    double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
3362
                    foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
3363
                    {
3364
                        if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLine2d)
3365
                        {
3366
                            Ingr.RAD2D.Line2d line2D = drawingObject as Ingr.RAD2D.Line2d;
3367

    
3368
                            double x1, y1, x2, y2;
3369
                            line2D.GetStartPoint(out x1, out y1);
3370
                            line2D.GetEndPoint(out x2, out y2);
3371
                            double tX1 = Math.Min(x1, x2), tY1 = Math.Min(y1, y2), tX2 = Math.Max(x1, x2), tY2 = Math.Max(y1, y2);
3372
                            if (minX > tX1)
3373
                                minX = tX1;
3374
                            if (minY > tY1)
3375
                                minY = tY1;
3376
                            if (maxX < tX2)
3377
                                maxX = tX2;
3378
                            if (maxY < tY2)
3379
                                maxY = tY2;
3380
                        }
3381
                    }
3382

    
3383
                    double width = Math.Abs(maxX - minX);
3384
                    double height = Math.Abs(maxY - minY);
3385
                    double ratio = width / height * 100;
3386
                    if (ratio > 99d && ratio < 101d)
3387
                    {
3388
                        result = true;
3389
                    }
3390
                    x = (maxX + minX) / 2d;
3391
                    y = (maxY + minY) / 2d;
3392
                    radius = width / 2d;
3393
                }
3394
            }
3395

    
3396
            return result;
3397
        }
3398

    
3399
        private void MoveSegmentBreak(string connectorID, LMLabelPersist labelPersist)
3400
        {
3401
            bool bFind = false;
3402
            double x, y, radius;
3403
            if (IsRhombus(labelPersist, out x, out y, out radius))
3404
            {
3405
                List<double[]> itemPoints = new List<double[]>();
3406
                LMConnector connector = dataSource.GetConnector(connectorID);
3407
                foreach (LMLabelPersist label in connector.LabelPersists)
3408
                {
3409
                    if (!"Active".Equals(label.get_ItemStatus()))
3410
                        continue;
3411

    
3412
                    if (!label.Id.Equals(labelPersist.Id))
3413
                    {
3414
                        double centerX, centerY, temp;
3415
                        if (IsRhombus(label, out centerX, out centerY, out temp))
3416
                        {
3417
                            bFind = true;
3418
                            itemPoints.Add(new double[] { centerX, centerY });
3419
                        }
3420
                    }
3421
                }
3422
                ReleaseCOMObjects(connector);
3423

    
3424

    
3425
                if (bFind)
3426
                {
3427
                    double[] startPoint = itemPoints.First();
3428
                    itemPoints.RemoveAt(0);
3429

    
3430
                    for (int i = 0; i < 8; i++)
3431
                    {
3432
                        double pointX = 0, pointY = 0;
3433
                        switch (i)
3434
                        {
3435
                            case 0:
3436
                                pointX = startPoint[0] + radius;
3437
                                pointY = startPoint[1] + radius;
3438
                                break;
3439
                            case 1:
3440
                                pointX = startPoint[0] + radius + radius;
3441
                                pointY = startPoint[1];
3442
                                break;
3443
                            case 2:
3444
                                pointX = startPoint[0] + radius;
3445
                                pointY = startPoint[1] - radius;
3446
                                break;
3447
                            case 3:
3448
                                pointX = startPoint[0];
3449
                                pointY = startPoint[1] - radius - radius;
3450
                                break;
3451
                            case 4:
3452
                                pointX = startPoint[0] - radius;
3453
                                pointY = startPoint[1] - radius;
3454
                                break;
3455
                            case 5:
3456
                                pointX = startPoint[0] - radius - radius;
3457
                                pointY = startPoint[1];
3458
                                break;
3459
                            case 6:
3460
                                pointX = startPoint[0] - radius;
3461
                                pointY = startPoint[1] + radius;
3462
                                break;
3463
                            case 7:
3464
                                pointX = startPoint[0];
3465
                                pointY = startPoint[1] + radius + radius;
3466
                                break;
3467
                            default:
3468
                                break;
3469
                        }
3470

    
3471
                        if (!ExistSegmentByPoint(pointX, pointY))
3472
                        {
3473
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
3474
                            if (dependency != null)
3475
                            {
3476
                                radApp.ActiveSelectSet.RemoveAll();
3477
                                radApp.ActiveSelectSet.Add(dependency);
3478
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3479
                                transform.DefineByMove2d(pointX - x, pointY - y);
3480
                                radApp.ActiveSelectSet.Transform(transform, true);
3481
                                radApp.ActiveSelectSet.RemoveAll();
3482
                            }
3483
                            break;
3484
                        }
3485
                    }
3486

    
3487
                    bool ExistSegmentByPoint(double pointX, double pointY)
3488
                    {
3489
                        bool result = false;
3490
                        foreach (var item in itemPoints)
3491
                        {
3492
                            double distance = SPPIDUtil.CalcPointToPointdDistance(item[0], item[1], pointX, pointY);
3493
                            if (Math.Truncate(distance * 1000000000d).Equals(0))
3494
                                result = true;
3495
                        }
3496
                        return result;
3497
                    }
3498
                }
3499
            }
3500

    
3501
            if (!bFind)
3502
                MoveSegmentBestLocation(labelPersist.get_GraphicOID().ToString(), new double[] { x - radius, y - radius, x + radius, y + radius }, itemRange);
3503
        }
3504

    
3505
        LMConnectors GetConnectors()
3506
        {
3507
            LMAFilter filter = new LMAFilter();
3508
            LMACriterion criterion1 = new LMACriterion();
3509
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3510
            criterion1.Operator = "=";
3511
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3512
            criterion1.Conjunctive = true;
3513
            filter.get_Criteria().Add(criterion1);
3514
            filter.ItemType = "Connector";
3515

    
3516
            LMACriterion criterion2 = new LMACriterion();
3517
            criterion2.SourceAttributeName = "ITEMSTATUS";
3518
            criterion2.Operator = "=";
3519
            criterion2.set_ValueAttribute("1");
3520
            criterion2.Conjunctive = true;
3521
            filter.get_Criteria().Add(criterion2);
3522

    
3523
            LMACriterion criterion3 = new LMACriterion();
3524
            criterion3.SourceAttributeName = "INSTOCKPILE";
3525
            criterion3.Operator = "=";
3526
            criterion3.set_ValueAttribute("1");
3527
            criterion3.Conjunctive = true;
3528
            filter.get_Criteria().Add(criterion3);
3529

    
3530
            LMConnectors items = new LMConnectors();
3531
            items.Collect(dataSource, Filter: filter);
3532

    
3533
            ReleaseCOMObjects(filter);
3534
            ReleaseCOMObjects(criterion1);
3535
            ReleaseCOMObjects(criterion2);
3536
            ReleaseCOMObjects(criterion3);
3537

    
3538
            return items;
3539
        }
3540
        LMSymbols GetSymbols()
3541
        {
3542
            LMAFilter filter = new LMAFilter();
3543
            LMACriterion criterion1 = new LMACriterion();
3544
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3545
            criterion1.Operator = "=";
3546
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3547
            criterion1.Conjunctive = true;
3548
            filter.get_Criteria().Add(criterion1);
3549
            filter.ItemType = "Symbol";
3550

    
3551
            LMACriterion criterion2 = new LMACriterion();
3552
            criterion2.SourceAttributeName = "ITEMSTATUS";
3553
            criterion2.Operator = "=";
3554
            criterion2.set_ValueAttribute("1");
3555
            criterion2.Conjunctive = true;
3556
            filter.get_Criteria().Add(criterion2);
3557

    
3558
            LMACriterion criterion3 = new LMACriterion();
3559
            criterion3.SourceAttributeName = "INSTOCKPILE";
3560
            criterion3.Operator = "=";
3561
            criterion3.set_ValueAttribute("1");
3562
            criterion3.Conjunctive = true;
3563
            filter.get_Criteria().Add(criterion3);
3564

    
3565
            LMSymbols items = new LMSymbols();
3566
            items.Collect(dataSource, Filter: filter);
3567

    
3568
            ReleaseCOMObjects(filter);
3569
            ReleaseCOMObjects(criterion1);
3570
            ReleaseCOMObjects(criterion2);
3571
            ReleaseCOMObjects(criterion3);
3572

    
3573
            return items;
3574
        }
3575

    
3576
        private void SetConnectorAndSymbolRange()
3577
        {
3578
            itemRange = new List<double[]>();
3579

    
3580
            LMConnectors connectors = GetConnectors();
3581
            foreach (LMConnector connector in connectors)
3582
            {
3583
                List<double[]> vertices = GetConnectorVertices(connector);
3584
                for (int i = 0; i < vertices.Count - 1; i++)
3585
                {
3586
                    double[] point1 = vertices[i];
3587
                    double[] point2 = vertices[i + 1];
3588
                    double x1 = Math.Min(point1[0], point2[0]), y1 = Math.Min(point1[1], point2[1]), x2 = Math.Max(point1[0], point2[0]), y2 = Math.Max(point1[1], point2[1]);
3589
                    double gap = 0.0001d;
3590
                    itemRange.Add(new double[] { x1 - gap, y1 - gap, x2 + gap, y2 + gap });
3591
                }
3592
                ReleaseCOMObjects(connector);
3593
            }
3594
            ReleaseCOMObjects(connectors);
3595

    
3596
            LMSymbols symbols = GetSymbols();
3597
            foreach (LMSymbol symbol in symbols)
3598
            {
3599
                string oid = symbol.get_GraphicOID().ToString();
3600
                DrawingObjectBase drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid];
3601
                if (drawingObject != null)
3602
                {
3603
                    double x1, y1, x2, y2;
3604
                    drawingObject.Range(out x1, out y1, out x2, out y2);
3605
                    itemRange.Add(new double[] { x1, y1, x2, y2 });
3606
                }
3607

    
3608
                ReleaseCOMObjects(symbol);
3609
            }
3610
            ReleaseCOMObjects(symbols);
3611
        }
3612

    
3613
        private void MoveSegmentBestLocation(string oid, double[] segmentRange, List<double[]> allRanges)
3614
        {
3615
            double minValue = Math.Min(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3616
            double maxValue = Math.Max(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3617

    
3618
            double maxX = 0, maxY = 0;
3619
            maxX = maxValue * 10;
3620
            maxY = minValue * 10;
3621

    
3622
            double move = minValue / 10d;
3623
            double textGap = minValue / 3d;
3624
            segmentRange = new double[] { segmentRange[0] - textGap, segmentRange[1] - textGap, segmentRange[2] + textGap, segmentRange[3] + textGap };
3625

    
3626

    
3627
            List<double[]> containRanges = new List<double[]>();
3628
            double[] findRange = new double[] {
3629
            segmentRange[0] - maxX, segmentRange[1] - maxY,
3630
            segmentRange[2] + maxX, segmentRange[3] + maxY};
3631

    
3632
            foreach (var range in allRanges)
3633
                if (SPPIDUtil.IsOverlap(findRange, range))
3634
                    containRanges.Add(range);
3635

    
3636
            double movePointX = 0, movePointY = 0, distance = double.MaxValue;
3637
            for (double x = 0; x < maxX; x = x + move)
3638
                for (double y = 0; y < maxY; y = y + move)
3639
                    for (int i = 0; i < 4; i++)
3640
                    {
3641
                        double tempX = 0d, tempY = 0d;
3642
                        switch (i)
3643
                        {
3644
                            case 0:
3645
                                tempX = x;
3646
                                tempY = y;
3647
                                break;
3648
                            case 1:
3649
                                tempX = -x;
3650
                                tempY = y;
3651
                                break;
3652
                            case 2:
3653
                                tempX = -x;
3654
                                tempY = -y;
3655
                                break;
3656
                            case 3:
3657
                                tempX = x;
3658
                                tempY = -y;
3659
                                break;
3660
                            default:
3661
                                break;
3662
                        }
3663

    
3664
                        bool result = true;
3665
                        double[] movedRange = new double[] { segmentRange[0] + tempX, segmentRange[1] + tempY, segmentRange[2] + tempX, segmentRange[3] + tempY };
3666
                        foreach (double[] range in containRanges)
3667
                        {
3668
                            if (SPPIDUtil.IsOverlap(range, movedRange))
3669
                            {
3670
                                result = false;
3671
                                break;
3672
                            }
3673
                        }
3674

    
3675
                        if (result)
3676
                        {
3677
                            //double tempDistance = Utils.CalcDistance(new double[] { 0, 0, 0 }, new double[] { tempX, tempY, 0 });
3678
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(0, 0, tempX, tempY);
3679
                            bool bChange = false;
3680
                            if (distance > tempDistance)
3681
                                bChange = true;
3682
                            else if (distance.Equals(tempDistance) && (movePointX.Equals(0d) || movePointY.Equals(0d)))
3683
                                bChange = true;
3684

    
3685
                            if (bChange)
3686
                            {
3687
                                distance = tempDistance;
3688
                                movePointX = tempX;
3689
                                movePointY = tempY;
3690
                            }
3691
                        }
3692
                    }
3693

    
3694
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3695
            if (dependency != null)
3696
            {
3697
                radApp.ActiveSelectSet.RemoveAll();
3698
                radApp.ActiveSelectSet.Add(dependency);
3699
                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3700
                transform.DefineByMove2d(movePointX, movePointY);
3701
                radApp.ActiveSelectSet.Transform(transform, true);
3702
                radApp.ActiveSelectSet.RemoveAll();
3703
            }
3704
        }
3705

    
3706
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3707
        {
3708
            LMConnector targetConnector = null;
3709
            Symbol targetSymbol = targetObj as Symbol;
3710
            Symbol connectedSymbol = connectedObj as Symbol;
3711
            Line targetLine = targetObj as Line;
3712
            Line connectedLine = connectedObj as Line;
3713
            if (targetSymbol != null && connectedSymbol != null)
3714
            {
3715
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3716
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3717

    
3718
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3719
                {
3720
                    if (connector.get_ItemStatus() != "Active")
3721
                        continue;
3722

    
3723
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3724
                    {
3725
                        targetConnector = connector;
3726
                        break;
3727
                    }
3728
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3729
                    {
3730
                        targetConnector = connector;
3731
                        break;
3732
                    }
3733
                }
3734

    
3735
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3736
                {
3737
                    if (connector.get_ItemStatus() != "Active")
3738
                        continue;
3739

    
3740
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3741
                    {
3742
                        targetConnector = connector;
3743
                        break;
3744
                    }
3745
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3746
                    {
3747
                        targetConnector = connector;
3748
                        break;
3749
                    }
3750
                }
3751

    
3752
                ReleaseCOMObjects(targetLMSymbol);
3753
                ReleaseCOMObjects(connectedLMSymbol);
3754
            }
3755
            else if (targetLine != null && connectedLine != null)
3756
            {
3757
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3758
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3759

    
3760
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3761
                {
3762
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3763
                    {
3764
                        if (targetConnector != null)
3765
                            break;
3766

    
3767
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3768
                        {
3769
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3770

    
3771
                            if (IsConnected(_LMConnector, connectedModelItem))
3772
                                targetConnector = _LMConnector;
3773
                            else
3774
                                ReleaseCOMObjects(_LMConnector);
3775
                        }
3776
                    }
3777

    
3778
                    ReleaseCOMObjects(targetModelItem);
3779
                }
3780
            }
3781
            else
3782
            {
3783
                LMSymbol connectedLMSymbol = null;
3784
                if (connectedSymbol != null)
3785
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3786
                else if (targetSymbol != null)
3787
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3788
                else
3789
                {
3790

    
3791
                }
3792
                LMModelItem targetModelItem = null;
3793
                if (targetLine != null)
3794
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3795
                else if (connectedLine != null)
3796
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3797
                else
3798
                {
3799

    
3800
                }
3801
                if (connectedLMSymbol != null && targetModelItem != null)
3802
                {
3803
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3804
                    {
3805
                        if (connector.get_ItemStatus() != "Active")
3806
                            continue;
3807

    
3808
                        if (IsConnected(connector, targetModelItem))
3809
                        {
3810
                            targetConnector = connector;
3811
                            break;
3812
                        }
3813
                    }
3814

    
3815
                    if (targetConnector == null)
3816
                    {
3817
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3818
                        {
3819
                            if (connector.get_ItemStatus() != "Active")
3820
                                continue;
3821

    
3822
                            if (IsConnected(connector, targetModelItem))
3823
                            {
3824
                                targetConnector = connector;
3825
                                break;
3826
                            }
3827
                        }
3828
                    }
3829
                }
3830

    
3831
            }
3832

    
3833
            return targetConnector;
3834
        }
3835

    
3836
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
3837
        {
3838
            double[] result = null;
3839
            Line targetLine = targetObj as Line;
3840
            Symbol targetSymbol = targetObj as Symbol;
3841
            Line connLine = connObj as Line;
3842
            Symbol connSymbol = connObj as Symbol;
3843
            location = SegmentLocation.None;
3844
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3845
            {
3846
                result = GetConnectorVertices(targetConnector)[0];
3847
                if (targetSymbol != null && connSymbol != null)
3848
                {
3849
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3850
                    result = new double[] { result[0], result[1] };
3851
                    if (slopeType == SlopeType.HORIZONTAL)
3852
                        location = SegmentLocation.Up;
3853
                    else if (slopeType == SlopeType.VERTICAL)
3854
                        location = SegmentLocation.Right;
3855
                }
3856
                else if (targetLine != null)
3857
                {
3858
                    result = new double[] { result[0], result[1] };
3859
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3860
                        location = SegmentLocation.Up;
3861
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3862
                        location = SegmentLocation.Right;
3863
                }
3864
                else if (connLine != null)
3865
                {
3866
                    result = new double[] { result[0], result[1] };
3867
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3868
                        location = SegmentLocation.Up;
3869
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3870
                        location = SegmentLocation.Right;
3871
                }
3872
            }
3873
            else
3874
            {
3875
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3876
                {
3877
                    Line line = connObj as Line;
3878
                    LMConnector connectedConnector = null;
3879
                    int connIndex = 0;
3880
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3881
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3882

    
3883
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3884

    
3885
                    ReleaseCOMObjects(modelItem);
3886
                    ReleaseCOMObjects(connectedConnector);
3887

    
3888
                    if (vertices.Count > 0)
3889
                    {
3890
                        if (connIndex == 1)
3891
                            result = vertices[0];
3892
                        else if (connIndex == 2)
3893
                            result = vertices[vertices.Count - 1];
3894

    
3895
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3896
                        {
3897
                            result = new double[] { result[0], result[1] };
3898
                            location = SegmentLocation.Up;
3899
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3900
                                location = location | SegmentLocation.Right;
3901
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3902
                                location = location | SegmentLocation.Left;
3903
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3904
                                location = location | SegmentLocation.Left;
3905
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3906
                                location = location | SegmentLocation.Right;
3907
                        }
3908
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3909
                        {
3910
                            result = new double[] { result[0], result[1] };
3911
                            location = SegmentLocation.Right;
3912
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3913
                                location = location | SegmentLocation.Up;
3914
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3915
                                location = location | SegmentLocation.Down;
3916
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3917
                                location = location | SegmentLocation.Down;
3918
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3919
                                location = location | SegmentLocation.Up;
3920
                        }
3921

    
3922
                    }
3923
                }
3924
                else
3925
                {
3926
                    Log.Write("error in GetSegemtPoint");
3927
                }
3928
            }
3929

    
3930
            return result;
3931
        }
3932

    
3933
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3934
        {
3935
            bool result = false;
3936

    
3937
            foreach (LMRepresentation rep in modelItem.Representations)
3938
            {
3939
                if (result)
3940
                    break;
3941

    
3942
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3943
                {
3944
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3945

    
3946
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3947
                        connector.ConnectItem1SymbolObject != null &&
3948
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3949
                    {
3950
                        result = true;
3951
                        ReleaseCOMObjects(_LMConnector);
3952
                        break;
3953
                    }
3954
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3955
                        connector.ConnectItem2SymbolObject != null &&
3956
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3957
                    {
3958
                        result = true;
3959
                        ReleaseCOMObjects(_LMConnector);
3960
                        break;
3961
                    }
3962
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3963
                        connector.ConnectItem1SymbolObject != null &&
3964
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3965
                    {
3966
                        result = true;
3967
                        ReleaseCOMObjects(_LMConnector);
3968
                        break;
3969
                    }
3970
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3971
                        connector.ConnectItem2SymbolObject != null &&
3972
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3973
                    {
3974
                        result = true;
3975
                        ReleaseCOMObjects(_LMConnector);
3976
                        break;
3977
                    }
3978

    
3979
                    ReleaseCOMObjects(_LMConnector);
3980
                }
3981
            }
3982

    
3983

    
3984
            return result;
3985
        }
3986

    
3987
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3988
        {
3989
            foreach (LMRepresentation rep in modelItem.Representations)
3990
            {
3991
                if (connectedConnector != null)
3992
                    break;
3993

    
3994
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3995
                {
3996
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3997

    
3998
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3999
                        connector.ConnectItem1SymbolObject != null &&
4000
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4001
                    {
4002
                        connectedConnector = _LMConnector;
4003
                        connectorIndex = 1;
4004
                        break;
4005
                    }
4006
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4007
                        connector.ConnectItem2SymbolObject != null &&
4008
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4009
                    {
4010
                        connectedConnector = _LMConnector;
4011
                        connectorIndex = 2;
4012
                        break;
4013
                    }
4014
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4015
                        connector.ConnectItem1SymbolObject != null &&
4016
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4017
                    {
4018
                        connectedConnector = _LMConnector;
4019
                        connectorIndex = 1;
4020
                        break;
4021
                    }
4022
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4023
                        connector.ConnectItem2SymbolObject != null &&
4024
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4025
                    {
4026
                        connectedConnector = _LMConnector;
4027
                        connectorIndex = 2;
4028
                        break;
4029
                    }
4030

    
4031
                    if (connectedConnector == null)
4032
                        ReleaseCOMObjects(_LMConnector);
4033
                }
4034
            }
4035
        }
4036

    
4037
        /// <summary>
4038
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
4039
        /// </summary>
4040
        /// <param name="modelItemID1"></param>
4041
        /// <param name="modelItemID2"></param>
4042
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
4043
        {
4044
            try
4045
            {
4046
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
4047
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
4048
                List<double[]> vertices1 = null;
4049
                string graphicOID1 = string.Empty;
4050
                if (connector1 != null)
4051
                {
4052
                    vertices1 = GetConnectorVertices(connector1);
4053
                    graphicOID1 = connector1.get_GraphicOID();
4054
                }
4055
                _LMAItem item1 = modelItem1.AsLMAItem();
4056
                ReleaseCOMObjects(connector1);
4057
                connector1 = null;
4058

    
4059
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
4060
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
4061
                List<double[]> vertices2 = null;
4062
                string graphicOID2 = string.Empty;
4063
                if (connector2 != null)
4064
                {
4065
                    vertices2 = GetConnectorVertices(connector2);
4066
                    graphicOID2 = connector2.get_GraphicOID();
4067
                }
4068
                _LMAItem item2 = modelItem2.AsLMAItem();
4069
                ReleaseCOMObjects(connector2);
4070
                connector2 = null;
4071

    
4072
                // item2가 item1으로 조인
4073
                _placement.PIDJoinRuns(ref item1, ref item2);
4074
                item1.Commit();
4075
                item2.Commit();
4076

    
4077
                string beforeID = string.Empty;
4078
                string afterID = string.Empty;
4079

    
4080
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
4081
                {
4082
                    beforeID = modelItem2.Id;
4083
                    afterID = modelItem1.Id;
4084
                    survivorId = afterID;
4085
                }
4086
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
4087
                {
4088
                    beforeID = modelItem1.Id;
4089
                    afterID = modelItem2.Id;
4090
                    survivorId = afterID;
4091
                }
4092
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
4093
                {
4094
                    int model1Cnt = GetConnectorCount(modelId1);
4095
                    int model2Cnt = GetConnectorCount(modelId2);
4096
                    if (model1Cnt == 0)
4097
                    {
4098
                        beforeID = modelItem1.Id;
4099
                        afterID = modelItem2.Id;
4100
                        survivorId = afterID;
4101
                    }
4102
                    else if (model2Cnt == 0)
4103
                    {
4104
                        beforeID = modelItem2.Id;
4105
                        afterID = modelItem1.Id;
4106
                        survivorId = afterID;
4107
                    }
4108
                    else
4109
                        survivorId = null;
4110
                }
4111
                else
4112
                {
4113
                    Log.Write("잘못된 경우");
4114
                    survivorId = null;
4115
                }
4116

    
4117
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
4118
                {
4119
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
4120
                    foreach (var line in lines)
4121
                        line.SPPID.ModelItemId = afterID;
4122
                }
4123

    
4124
                ReleaseCOMObjects(modelItem1);
4125
                ReleaseCOMObjects(item1);
4126
                ReleaseCOMObjects(modelItem2);
4127
                ReleaseCOMObjects(item2);
4128
            }
4129
            catch (Exception ex)
4130
            {
4131
                Log.Write("Join Error");
4132
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
4133
            }
4134
        }
4135

    
4136
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
4137
        {
4138
            bool result = false;
4139
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
4140
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
4141
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
4142

    
4143
            foreach (var item in endBreaks)
4144
            {
4145
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
4146
                {
4147
                    result = true;
4148
                    break;
4149
                }
4150
            }
4151

    
4152
            return result;
4153
        }
4154
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
4155
        {
4156
            List<string> temp = new List<string>();
4157
            List<LMConnector> connectors = new List<LMConnector>();
4158
            foreach (LMConnector connector in symbol.Avoid1Connectors)
4159
            {
4160
                if (connector.get_ItemStatus() != "Active")
4161
                    continue;
4162

    
4163
                LMModelItem modelItem = connector.ModelItemObject;
4164
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4165
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4166
                    temp.Add(modelItem.Id);
4167

    
4168
                if (temp.Contains(modelItem.Id) &&
4169
                    connOtherSymbol != null &&
4170
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4171
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4172
                    temp.Remove(modelItem.Id);
4173

    
4174

    
4175
                if (temp.Contains(modelItem.Id))
4176
                    connectors.Add(connector);
4177
                ReleaseCOMObjects(connOtherSymbol);
4178
                connOtherSymbol = null;
4179
                ReleaseCOMObjects(modelItem);
4180
                modelItem = null;
4181
            }
4182

    
4183
            foreach (LMConnector connector in symbol.Avoid2Connectors)
4184
            {
4185
                if (connector.get_ItemStatus() != "Active")
4186
                    continue;
4187

    
4188
                LMModelItem modelItem = connector.ModelItemObject;
4189
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4190
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4191
                    temp.Add(modelItem.Id);
4192

    
4193
                if (temp.Contains(modelItem.Id) &&
4194
                    connOtherSymbol != null &&
4195
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4196
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4197
                    temp.Remove(modelItem.Id);
4198

    
4199
                if (temp.Contains(modelItem.Id))
4200
                    connectors.Add(connector);
4201
                ReleaseCOMObjects(connOtherSymbol);
4202
                connOtherSymbol = null;
4203
                ReleaseCOMObjects(modelItem);
4204
                modelItem = null;
4205
            }
4206

    
4207

    
4208
            List<string> result = new List<string>();
4209
            string originalName = GetSPPIDFileName(modelId);
4210
            foreach (var connector in connectors)
4211
            {
4212
                string fileName = GetSPPIDFileName(connector.ModelItemID);
4213
                if (originalName == fileName)
4214
                    result.Add(connector.ModelItemID);
4215
                else
4216
                {
4217
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
4218
                        result.Add(connector.ModelItemID);
4219
                    else
4220
                    {
4221
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
4222
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
4223
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
4224
                            result.Add(connector.ModelItemID);
4225
                    }
4226
                }
4227
            }
4228

    
4229
            foreach (var connector in connectors)
4230
                ReleaseCOMObjects(connector);
4231

    
4232
            return result;
4233

    
4234

    
4235
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
4236
            {
4237
                LMSymbol findResult = null;
4238
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
4239
                    findResult = connector.ConnectItem1SymbolObject;
4240
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
4241
                    findResult = connector.ConnectItem2SymbolObject;
4242

    
4243
                return findResult;
4244
            }
4245
        }
4246

    
4247
        /// <summary>
4248
        /// PipeRun의 좌표를 가져오는 메서드
4249
        /// </summary>
4250
        /// <param name="modelId"></param>
4251
        /// <returns></returns>
4252
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
4253
        {
4254
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
4255
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
4256

    
4257
            if (modelItem != null)
4258
            {
4259
                foreach (LMRepresentation rep in modelItem.Representations)
4260
                {
4261
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4262
                    {
4263
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4264
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
4265
                        {
4266
                            ReleaseCOMObjects(_LMConnector);
4267
                            _LMConnector = null;
4268
                            continue;
4269
                        }
4270
                        connectorVertices.Add(_LMConnector, new List<double[]>());
4271
                        dynamic OID = rep.get_GraphicOID().ToString();
4272
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4273
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4274
                        int verticesCount = lineStringGeometry.VertexCount;
4275
                        double[] vertices = null;
4276
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
4277
                        for (int i = 0; i < verticesCount; i++)
4278
                        {
4279
                            double x = 0;
4280
                            double y = 0;
4281
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4282
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
4283
                        }
4284
                    }
4285
                }
4286

    
4287
                ReleaseCOMObjects(modelItem);
4288
            }
4289

    
4290
            return connectorVertices;
4291
        }
4292

    
4293
        private List<double[]> GetConnectorVertices(LMConnector connector)
4294
        {
4295
            List<double[]> vertices = new List<double[]>();
4296
            if (connector != null)
4297
            {
4298
                dynamic OID = connector.get_GraphicOID().ToString();
4299
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4300
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4301
                int verticesCount = lineStringGeometry.VertexCount;
4302
                double[] value = null;
4303
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4304
                for (int i = 0; i < verticesCount; i++)
4305
                {
4306
                    double x = 0;
4307
                    double y = 0;
4308
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4309
                    vertices.Add(new double[] { x, y });
4310
                }
4311
            }
4312
            return vertices;
4313
        }
4314

    
4315
        private double GetConnectorDistance(LMConnector connector)
4316
        {
4317
            double result = 0;
4318
            List<double[]> vertices = new List<double[]>();
4319
            if (connector != null)
4320
            {
4321
                dynamic OID = connector.get_GraphicOID().ToString();
4322
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4323
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4324
                int verticesCount = lineStringGeometry.VertexCount;
4325
                double[] value = null;
4326
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4327
                for (int i = 0; i < verticesCount; i++)
4328
                {
4329
                    double x = 0;
4330
                    double y = 0;
4331
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4332
                    vertices.Add(new double[] { x, y });
4333
                    if (vertices.Count > 1)
4334
                    {
4335
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
4336
                    }
4337
                }
4338
            }
4339
            return result;
4340
        }
4341
        private double[] GetConnectorRange(LMConnector connector)
4342
        {
4343
            double[] result = null;
4344
            List<double[]> vertices = new List<double[]>();
4345
            if (connector != null)
4346
            {
4347
                dynamic OID = connector.get_GraphicOID().ToString();
4348
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4349
                double minX = 0;
4350
                double minY = 0;
4351
                double maxX = 0;
4352
                double maxY = 0;
4353

    
4354
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
4355
                result = new double[] { minX, minY, maxX, maxY };
4356
            }
4357
            return result;
4358
        }
4359
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
4360
        {
4361
            List<double[]> vertices = null;
4362
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
4363
            if (drawingObject != null)
4364
            {
4365
                vertices = new List<double[]>();
4366
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4367
                int verticesCount = lineStringGeometry.VertexCount;
4368
                double[] value = null;
4369
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4370
                for (int i = 0; i < verticesCount; i++)
4371
                {
4372
                    double x = 0;
4373
                    double y = 0;
4374
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4375
                    vertices.Add(new double[] { x, y });
4376
                }
4377
            }
4378
            return vertices;
4379
        }
4380
        /// <summary>
4381
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
4382
        /// </summary>
4383
        /// <param name="connectorVertices"></param>
4384
        /// <param name="connX"></param>
4385
        /// <param name="connY"></param>
4386
        /// <returns></returns>
4387
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
4388
        {
4389
            double length = double.MaxValue;
4390
            LMConnector targetConnector = null;
4391
            foreach (var item in connectorVertices)
4392
            {
4393
                List<double[]> points = item.Value;
4394
                for (int i = 0; i < points.Count - 1; i++)
4395
                {
4396
                    double[] point1 = points[i];
4397
                    double[] point2 = points[i + 1];
4398
                    double x1 = Math.Min(point1[0], point2[0]);
4399
                    double y1 = Math.Min(point1[1], point2[1]);
4400
                    double x2 = Math.Max(point1[0], point2[0]);
4401
                    double y2 = Math.Max(point1[1], point2[1]);
4402

    
4403
                    if ((x1 <= connX && x2 >= connX) ||
4404
                        (y1 <= connY && y2 >= connY))
4405
                    {
4406
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
4407
                        if (length >= distance)
4408
                        {
4409
                            targetConnector = item.Key;
4410
                            length = distance;
4411
                        }
4412

    
4413
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
4414
                        if (length >= distance)
4415
                        {
4416
                            targetConnector = item.Key;
4417
                            length = distance;
4418
                        }
4419
                    }
4420
                }
4421
            }
4422

    
4423
            // 못찾았을때.
4424
            length = double.MaxValue;
4425
            if (targetConnector == null)
4426
            {
4427
                foreach (var item in connectorVertices)
4428
                {
4429
                    List<double[]> points = item.Value;
4430

    
4431
                    foreach (double[] point in points)
4432
                    {
4433
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
4434
                        if (length >= distance)
4435
                        {
4436
                            targetConnector = item.Key;
4437
                            length = distance;
4438
                        }
4439
                    }
4440
                }
4441
            }
4442

    
4443
            return targetConnector;
4444
        }
4445

    
4446
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
4447
        {
4448
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4449
            if (vertices.Count == 0)
4450
                return null;
4451

    
4452
            double length = double.MaxValue;
4453
            LMConnector targetConnector = null;
4454
            double[] resultPoint = null;
4455
            List<double[]> targetVertices = null;
4456

    
4457
            // Vertices 포인트에 제일 가까운곳
4458
            foreach (var item in vertices)
4459
            {
4460
                List<double[]> points = item.Value;
4461
                for (int i = 0; i < points.Count; i++)
4462
                {
4463
                    double[] point = points[i];
4464
                    double tempX = point[0];
4465
                    double tempY = point[1];
4466

    
4467
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4468
                    if (length >= distance)
4469
                    {
4470
                        targetConnector = item.Key;
4471
                        length = distance;
4472
                        resultPoint = point;
4473
                        targetVertices = item.Value;
4474
                    }
4475
                }
4476
            }
4477

    
4478
            // Vertices Cross에 제일 가까운곳
4479
            foreach (var item in vertices)
4480
            {
4481
                List<double[]> points = item.Value;
4482
                for (int i = 0; i < points.Count - 1; i++)
4483
                {
4484
                    double[] point1 = points[i];
4485
                    double[] point2 = points[i + 1];
4486

    
4487
                    double maxLineX = Math.Max(point1[0], point2[0]);
4488
                    double minLineX = Math.Min(point1[0], point2[0]);
4489
                    double maxLineY = Math.Max(point1[1], point2[1]);
4490
                    double minLineY = Math.Min(point1[1], point2[1]);
4491

    
4492
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4493

    
4494
                    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]);
4495
                    if (crossingPoint != null)
4496
                    {
4497
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4498
                        if (length >= distance)
4499
                        {
4500
                            if (slope == SlopeType.Slope &&
4501
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4502
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4503
                            {
4504
                                targetConnector = item.Key;
4505
                                length = distance;
4506
                                resultPoint = crossingPoint;
4507
                                targetVertices = item.Value;
4508
                            }
4509
                            else if (slope == SlopeType.HORIZONTAL &&
4510
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4511
                            {
4512
                                targetConnector = item.Key;
4513
                                length = distance;
4514
                                resultPoint = crossingPoint;
4515
                                targetVertices = item.Value;
4516
                            }
4517
                            else if (slope == SlopeType.VERTICAL &&
4518
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4519
                            {
4520
                                targetConnector = item.Key;
4521
                                length = distance;
4522
                                resultPoint = crossingPoint;
4523
                                targetVertices = item.Value;
4524
                            }
4525
                        }
4526
                    }
4527
                }
4528
            }
4529

    
4530
            foreach (var item in vertices)
4531
                if (item.Key != null && item.Key != targetConnector)
4532
                    ReleaseCOMObjects(item.Key);
4533

    
4534
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4535
            {
4536
                double tempResultX = resultPoint[0];
4537
                double tempResultY = resultPoint[1];
4538
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4539

    
4540
                GridSetting gridSetting = GridSetting.GetInstance();
4541

    
4542
                for (int i = 0; i < targetVertices.Count; i++)
4543
                {
4544
                    double[] point = targetVertices[i];
4545
                    double tempX = targetVertices[i][0];
4546
                    double tempY = targetVertices[i][1];
4547
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4548
                    if (tempX == tempResultX && tempY == tempResultY)
4549
                    {
4550
                        if (i == 0)
4551
                        {
4552
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4553
                            bool containZeroLength = false;
4554
                            if (connSymbol != null)
4555
                            {
4556
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4557
                                {
4558
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4559
                                        containZeroLength = true;
4560
                                }
4561
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4562
                                {
4563
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4564
                                        containZeroLength = true;
4565
                                }
4566
                            }
4567

    
4568
                            if (connSymbol == null ||
4569
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4570
                                containZeroLength)
4571
                            {
4572
                                bool bCalcX = false;
4573
                                bool bCalcY = false;
4574
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4575
                                    bCalcX = true;
4576
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4577
                                    bCalcY = true;
4578
                                else
4579
                                {
4580
                                    bCalcX = true;
4581
                                    bCalcY = true;
4582
                                }
4583

    
4584
                                if (bCalcX)
4585
                                {
4586
                                    double nextX = targetVertices[i + 1][0];
4587
                                    double newX = 0;
4588
                                    if (nextX > tempX)
4589
                                    {
4590
                                        newX = tempX + gridSetting.Length;
4591
                                        if (newX > nextX)
4592
                                            newX = (point[0] + nextX) / 2;
4593
                                    }
4594
                                    else
4595
                                    {
4596
                                        newX = tempX - gridSetting.Length;
4597
                                        if (newX < nextX)
4598
                                            newX = (point[0] + nextX) / 2;
4599
                                    }
4600
                                    resultPoint = new double[] { newX, resultPoint[1] };
4601
                                }
4602

    
4603
                                if (bCalcY)
4604
                                {
4605
                                    double nextY = targetVertices[i + 1][1];
4606
                                    double newY = 0;
4607
                                    if (nextY > tempY)
4608
                                    {
4609
                                        newY = tempY + gridSetting.Length;
4610
                                        if (newY > nextY)
4611
                                            newY = (point[1] + nextY) / 2;
4612
                                    }
4613
                                    else
4614
                                    {
4615
                                        newY = tempY - gridSetting.Length;
4616
                                        if (newY < nextY)
4617
                                            newY = (point[1] + nextY) / 2;
4618
                                    }
4619
                                    resultPoint = new double[] { resultPoint[0], newY };
4620
                                }
4621
                            }
4622
                        }
4623
                        else if (i == targetVertices.Count - 1)
4624
                        {
4625
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4626
                            bool containZeroLength = false;
4627
                            if (connSymbol != null)
4628
                            {
4629
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4630
                                {
4631
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4632
                                        containZeroLength = true;
4633
                                }
4634
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4635
                                {
4636
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4637
                                        containZeroLength = true;
4638
                                }
4639
                            }
4640

    
4641
                            if (connSymbol == null ||
4642
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4643
                                containZeroLength)
4644
                            {
4645
                                bool bCalcX = false;
4646
                                bool bCalcY = false;
4647
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4648
                                    bCalcX = true;
4649
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4650
                                    bCalcY = true;
4651
                                else
4652
                                {
4653
                                    bCalcX = true;
4654
                                    bCalcY = true;
4655
                                }
4656

    
4657
                                if (bCalcX)
4658
                                {
4659
                                    double nextX = targetVertices[i - 1][0];
4660
                                    double newX = 0;
4661
                                    if (nextX > tempX)
4662
                                    {
4663
                                        newX = tempX + gridSetting.Length;
4664
                                        if (newX > nextX)
4665
                                            newX = (point[0] + nextX) / 2;
4666
                                    }
4667
                                    else
4668
                                    {
4669
                                        newX = tempX - gridSetting.Length;
4670
                                        if (newX < nextX)
4671
                                            newX = (point[0] + nextX) / 2;
4672
                                    }
4673
                                    resultPoint = new double[] { newX, resultPoint[1] };
4674
                                }
4675

    
4676
                                if (bCalcY)
4677
                                {
4678
                                    double nextY = targetVertices[i - 1][1];
4679
                                    double newY = 0;
4680
                                    if (nextY > tempY)
4681
                                    {
4682
                                        newY = tempY + gridSetting.Length;
4683
                                        if (newY > nextY)
4684
                                            newY = (point[1] + nextY) / 2;
4685
                                    }
4686
                                    else
4687
                                    {
4688
                                        newY = tempY - gridSetting.Length;
4689
                                        if (newY < nextY)
4690
                                            newY = (point[1] + nextY) / 2;
4691
                                    }
4692
                                    resultPoint = new double[] { resultPoint[0], newY };
4693
                                }
4694
                            }
4695
                        }
4696
                        break;
4697
                    }
4698
                }
4699
            }
4700

    
4701
            x = resultPoint[0];
4702
            y = resultPoint[1];
4703

    
4704
            return targetConnector;
4705
        }
4706

    
4707
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4708
        {
4709
            LMConnector result = null;
4710
            List<LMConnector> connectors = new List<LMConnector>();
4711
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4712

    
4713
            if (modelItem != null)
4714
            {
4715
                foreach (LMRepresentation rep in modelItem.Representations)
4716
                {
4717
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4718
                        connectors.Add(dataSource.GetConnector(rep.Id));
4719
                }
4720

    
4721
                ReleaseCOMObjects(modelItem);
4722
            }
4723

    
4724
            if (connectors.Count == 1)
4725
                result = connectors[0];
4726
            else
4727
                foreach (var item in connectors)
4728
                    ReleaseCOMObjects(item);
4729

    
4730
            return result;
4731
        }
4732

    
4733
        private LMConnector GetLMConnectorFirst(string modelItemID)
4734
        {
4735
            LMConnector result = null;
4736
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4737

    
4738
            if (modelItem != null)
4739
            {
4740
                foreach (LMRepresentation rep in modelItem.Representations)
4741
                {
4742
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" &&
4743
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4744
                    {
4745
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4746
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4747
                        {
4748
                            result = connector;
4749
                            break;
4750
                        }
4751
                        else
4752
                        {
4753
                            ReleaseCOMObjects(connector);
4754
                            connector = null;
4755
                        }
4756
                    }
4757
                }
4758
                ReleaseCOMObjects(modelItem);
4759
                modelItem = null;
4760
            }
4761

    
4762
            return result;
4763
        }
4764

    
4765
        private int GetConnectorCount(string modelItemID)
4766
        {
4767
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4768
            int result = 0;
4769
            if (modelItem != null)
4770
            {
4771
                foreach (LMRepresentation rep in modelItem.Representations)
4772
                {
4773
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4774
                        result++;
4775
                    ReleaseCOMObjects(rep);
4776
                }
4777
                ReleaseCOMObjects(modelItem);
4778
            }
4779

    
4780
            return result;
4781
        }
4782

    
4783
        public List<string> GetRepresentations(string modelItemID)
4784
        {
4785
            List<string> result = new List<string>(); ;
4786
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4787
            if (modelItem != null)
4788
            {
4789
                foreach (LMRepresentation rep in modelItem.Representations)
4790
                {
4791
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4792
                        result.Add(rep.Id);
4793
                }
4794
                ReleaseCOMObjects(modelItem);
4795
            }
4796

    
4797
            return result;
4798
        }
4799

    
4800
        private void LineNumberModeling(LineNumber lineNumber)
4801
        {
4802
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4803
            if (line != null)
4804
            {
4805
                double x = 0;
4806
                double y = 0;
4807
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4808

    
4809
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4810
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4811
                if (connectedLMConnector != null)
4812
                {
4813
                    Array points = new double[] { 0, x, y };
4814
                    lineNumber.SPPID.SPPID_X = x;
4815
                    lineNumber.SPPID.SPPID_Y = y;
4816
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4817

    
4818
                    if (_LmLabelPresist != null)
4819
                    {
4820
                        _LmLabelPresist.Commit();
4821
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4822
                        ReleaseCOMObjects(_LmLabelPresist);
4823
                    }
4824
                }
4825

    
4826
                foreach (var item in connectorVertices)
4827
                    ReleaseCOMObjects(item.Key);
4828
            }
4829
        }
4830
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4831
        {
4832
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4833
            if (line == null || line.SPPID.Vertices == null)
4834
                return;
4835

    
4836
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4837
            {
4838
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4839
                if (removeLabel != null)
4840
                {
4841
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4842
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4843

    
4844
                    GridSetting gridSetting = GridSetting.GetInstance();
4845
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4846

    
4847
                    double[] labelRange = null;
4848
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4849
                    List<double[]> vertices = GetConnectorVertices(connector);
4850

    
4851
                    double[] resultStart = null;
4852
                    double[] resultEnd = null;
4853
                    double distance = double.MaxValue;
4854
                    for (int i = 0; i < vertices.Count - 1; i++)
4855
                    {
4856
                        double[] startPoint = vertices[i];
4857
                        double[] endPoint = vertices[i + 1];
4858
                        foreach (var item in line.SPPID.Vertices)
4859
                        {
4860
                            double[] lineStartPoint = item[0];
4861
                            double[] lineEndPoint = item[item.Count - 1];
4862

    
4863
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4864
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4865
                            if (tempDistance < distance)
4866
                            {
4867
                                distance = tempDistance;
4868
                                resultStart = startPoint;
4869
                                resultEnd = endPoint;
4870
                            }
4871
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4872
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4873
                            if (tempDistance < distance)
4874
                            {
4875
                                distance = tempDistance;
4876
                                resultStart = startPoint;
4877
                                resultEnd = endPoint;
4878
                            }
4879
                        }
4880
                    }
4881

    
4882
                    if (resultStart != null && resultEnd != null)
4883
                    {
4884
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4885
                        double lineStartX = 0;
4886
                        double lineStartY = 0;
4887
                        double lineEndX = 0;
4888
                        double lineEndY = 0;
4889
                        double lineNumberX = 0;
4890
                        double lineNumberY = 0;
4891
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4892
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4893

    
4894
                        double lineX = (lineStartX + lineEndX) / 2;
4895
                        double lineY = (lineStartY + lineEndY) / 2;
4896
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4897
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4898

    
4899
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4900
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4901
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4902
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4903

    
4904
                        double offsetX = 0;
4905
                        double offsetY = 0;
4906
                        if (slope == SlopeType.HORIZONTAL)
4907
                        {
4908
                            // Line Number 아래
4909
                            if (lineY < lineNumberY)
4910
                            {
4911
                                offsetX = labelCenterX - SPPIDCenterX;
4912
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4913
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4914
                            }
4915
                            // Line Number 위
4916
                            else
4917
                            {
4918
                                offsetX = labelCenterX - SPPIDCenterX;
4919
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4920
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4921
                            }
4922
                        }
4923
                        else if (slope == SlopeType.VERTICAL)
4924
                        {
4925
                            // Line Number 오르쪽
4926
                            if (lineX < lineNumberX)
4927
                            {
4928
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4929
                                offsetY = labelCenterY - SPPIDCenterY;
4930
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4931
                            }
4932
                            // Line Number 왼쪽
4933
                            else
4934
                            {
4935
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4936
                                offsetY = labelCenterY - SPPIDCenterY;
4937
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4938
                            }
4939
                        }
4940

    
4941
                        if (offsetY != 0 || offsetY != 0)
4942
                        {
4943
                            if (connector.ConnectItem1SymbolObject != null &&
4944
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4945
                            {
4946
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4947

    
4948
                                double x1, y1, x2, y2, originX, originY;
4949
                                symbol.Range(out x1, out y1, out x2, out y2);
4950
                                symbol.GetOrigin(out originX, out originY);
4951
                                if (originX < lineNumber.SPPID.SPPID_X)
4952
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4953
                                else
4954
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4955
                            }
4956
                            else if (connector.ConnectItem2SymbolObject != null &&
4957
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4958
                            {
4959
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4960

    
4961
                                double x1, y1, x2, y2, originX, originY;
4962
                                symbol.Range(out x1, out y1, out x2, out y2);
4963
                                symbol.GetOrigin(out originX, out originY);
4964
                                if (originX < lineNumber.SPPID.SPPID_X)
4965
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4966
                                else
4967
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4968
                            }
4969

    
4970
                            radApp.ActiveSelectSet.RemoveAll();
4971
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
4972
                            if (dependency != null)
4973
                            {
4974
                                radApp.ActiveSelectSet.Add(dependency);
4975
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4976
                                transform.DefineByMove2d(-offsetX, -offsetY);
4977
                                radApp.ActiveSelectSet.Transform(transform, true);
4978
                                radApp.ActiveSelectSet.RemoveAll();
4979
                            }
4980
                        }
4981

    
4982
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4983
                        {
4984
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4985
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4986
                        }
4987
                    }
4988

    
4989

    
4990
                    ReleaseCOMObjects(connector);
4991
                    connector = null;
4992
                }
4993

    
4994
                ReleaseCOMObjects(removeLabel);
4995
                removeLabel = null;
4996
            }
4997
        }
4998
        /// <summary>
4999
        /// Flow Mark Modeling
5000
        /// </summary>
5001
        /// <param name="line"></param>
5002
        private void FlowMarkModeling(Line line)
5003
        {
5004
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
5005
            {
5006
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
5007
                if (connector != null)
5008
                {
5009
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
5010
                    List<double[]> vertices = GetConnectorVertices(connector);
5011
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
5012
                    double[] point = vertices[vertices.Count - 1];
5013
                    Array array = new double[] { 0, point[0], point[1] };
5014
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, null, null, LabeledItem: connector.AsLMRepresentation());
5015
                    if (_LMLabelPersist != null)
5016
                    {
5017
                        _LMLabelPersist.Commit();
5018
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
5019
                        ReleaseCOMObjects(_LMLabelPersist);
5020
                    }
5021
                }
5022
            }
5023
        }
5024

    
5025
        /// <summary>
5026
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
5027
        /// </summary>
5028
        /// <param name="lineNumber"></param>
5029
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
5030
        {
5031
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
5032
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
5033
            {
5034
                if (a.ATTRIBUTE == "Tag Seq No")
5035
                    return 1;
5036
                else if (b.ATTRIBUTE == "Tag Seq No")
5037
                    return -1;
5038

    
5039
                return 0;
5040
            }
5041

    
5042
            foreach (LineRun run in lineNumber.RUNS)
5043
            {
5044
                foreach (var item in run.RUNITEMS)
5045
                {
5046
                    if (item.GetType() == typeof(Line))
5047
                    {
5048
                        Line line = item as Line;
5049
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
5050
                        {
5051
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5052
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5053
                            {
5054
                                foreach (var attribute in lineNumber.ATTRIBUTES)
5055
                                {
5056
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
5057
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5058
                                    {
5059
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5060
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
5061
                                        {
5062
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5063
                                            if (_FluidSystemAttribute != null)
5064
                                            {
5065
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
5066
                                                if (dt.Rows.Count == 1)
5067
                                                {
5068
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5069
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5070
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5071
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5072
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5073

    
5074
                                                    if (_LMAAttribute != null)
5075
                                                    {
5076
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5077
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5078
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
5079
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5080
                                                    }
5081
                                                }
5082
                                                if (dt != null)
5083
                                                    dt.Dispose();
5084
                                            }
5085
                                        }
5086
                                        else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(attribute.VALUE) && _LMAAttribute != null)
5087
                                        {
5088
                                            DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", attribute.VALUE));
5089

    
5090
                                            if (rows.Length.Equals(1))
5091
                                            {
5092
                                                if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5093
                                                    attribute.VALUE = rows[0]["MetricStr"].ToString();
5094
                                                else
5095
                                                    attribute.VALUE = rows[0]["InchStr"].ToString();
5096

    
5097
                                                if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5098
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5099
                                                else if (_LMAAttribute.get_Value() != attribute.VALUE)
5100
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5101
                                            }
5102
                                        }
5103
                                        else if (_LMAAttribute != null)
5104
                                        {
5105
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5106
                                                _LMAAttribute.set_Value(attribute.VALUE);
5107
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
5108
                                                _LMAAttribute.set_Value(attribute.VALUE);
5109
                                        }
5110
                                    }
5111
                                }
5112
                                _LMModelItem.Commit();
5113
                            }
5114
                            if (_LMModelItem != null)
5115
                                ReleaseCOMObjects(_LMModelItem);
5116
                            endLine.Add(line.SPPID.ModelItemId);
5117
                        }
5118
                    }
5119
                }
5120
            }
5121
        }
5122

    
5123
        /// <summary>
5124
        /// Symbol Attribute 입력 메서드
5125
        /// </summary>
5126
        /// <param name="item"></param>
5127
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
5128
        {
5129
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
5130
            string sRep = null;
5131
            string sModelID = null;
5132
            if (targetItem.GetType() == typeof(Symbol))
5133
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
5134
            else if (targetItem.GetType() == typeof(Equipment))
5135
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
5136
            else if (targetItem.GetType() == typeof(Line))
5137
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
5138

    
5139
            if (!string.IsNullOrEmpty(sRep))
5140
            {
5141
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
5142
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
5143
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5144

    
5145
                foreach (var item in targetAttributes)
5146
                {
5147
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5148
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5149
                    {
5150
                        if (!mapping.IsText)
5151
                        {
5152
                            LMAAttribute _LMAAttribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5153
                            if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5154
                            {
5155
                                DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5156

    
5157
                                if (rows.Length.Equals(1))
5158
                                {
5159
                                    if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5160
                                        item.VALUE = rows[0]["MetricStr"].ToString();
5161
                                    else
5162
                                        item.VALUE = rows[0]["InchStr"].ToString();
5163

    
5164
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5165
                                        _LMAAttribute.set_Value(item.VALUE);
5166
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5167
                                        _LMAAttribute.set_Value(item.VALUE);
5168
                                }
5169
                            }
5170
                            else if (_LMAAttribute != null)
5171
                            {
5172
                                _LMAAttribute.set_Value(item.VALUE);
5173
                                // OPC 일경우 Attribute 저장
5174
                                if (targetItem.GetType() == typeof(Symbol))
5175
                                {
5176
                                    Symbol symbol = targetItem as Symbol;
5177
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
5178
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
5179
                                }
5180
                            }
5181
                        }
5182
                        else
5183
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
5184
                    }
5185
                }
5186
                _LMModelItem.Commit();
5187

    
5188
                ReleaseCOMObjects(_Attributes);
5189
                ReleaseCOMObjects(_LMModelItem);
5190
                ReleaseCOMObjects(_LMSymbol);
5191
            }
5192
            else if (!string.IsNullOrEmpty(sModelID))
5193
            {
5194
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
5195
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5196

    
5197
                foreach (var item in targetAttributes)
5198
                {
5199
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5200
                    if (mapping == null)
5201
                        continue;
5202
                    
5203
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5204
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
5205
                    {
5206
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5207
                        if (_FluidSystemAttribute != null)
5208
                        {
5209
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
5210
                            if (dt.Rows.Count == 1)
5211
                            {
5212
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5213
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5214
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5215
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5216
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5217

    
5218
                                if (_LMAAttribute != null)
5219
                                {
5220
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5221
                                        _LMAAttribute.set_Value(item.VALUE);
5222
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5223
                                        _LMAAttribute.set_Value(item.VALUE);
5224
                                }
5225
                            }
5226
                            if (dt != null)
5227
                                dt.Dispose();
5228
                        }
5229
                    }
5230
                    else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5231
                    {
5232
                        DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5233

    
5234
                        if (rows.Length.Equals(1))
5235
                        {
5236
                            if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5237
                                item.VALUE = rows[0]["MetricStr"].ToString();
5238
                            else
5239
                                item.VALUE = rows[0]["InchStr"].ToString();
5240

    
5241
                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5242
                                _LMAAttribute.set_Value(item.VALUE);
5243
                            else if (_LMAAttribute.get_Value() != item.VALUE)
5244
                                _LMAAttribute.set_Value(item.VALUE);
5245
                        }
5246
                    }
5247
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5248
                    {
5249
                        if (!mapping.IsText)
5250
                        {
5251
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5252
                            if (_Attribute != null)
5253
                                _Attribute.set_Value(item.VALUE);
5254
                        }
5255
                    }
5256
                }
5257
                _LMModelItem.Commit();
5258

    
5259
                ReleaseCOMObjects(_Attributes);
5260
                ReleaseCOMObjects(_LMModelItem);
5261
            }
5262
        }
5263

    
5264
        /// <summary>
5265
        /// Input SpecBreak Attribute
5266
        /// </summary>
5267
        /// <param name="specBreak"></param>
5268
        private void InputSpecBreakAttribute(SpecBreak specBreak)
5269
        {
5270
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
5271
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
5272

    
5273
            if (upStreamObj != null &&
5274
                downStreamObj != null)
5275
            {
5276
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
5277

    
5278
                if (targetLMConnector != null)
5279
                {
5280
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
5281
                    {
5282
                        string symbolPath = _LMLabelPersist.get_FileName();
5283
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
5284
                        if (mapping != null)
5285
                        {
5286
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
5287
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5288
                            {
5289
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
5290
                                if (values.Length == 2)
5291
                                {
5292
                                    string upStreamValue = values[0];
5293
                                    string downStreamValue = values[1];
5294

    
5295
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
5296
                                }
5297
                            }
5298
                        }
5299
                    }
5300

    
5301
                    ReleaseCOMObjects(targetLMConnector);
5302
                }
5303
            }
5304

    
5305

    
5306
            #region 내부에서만 쓰는 메서드
5307
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
5308
            {
5309
                Symbol upStreamSymbol = _upStreamObj as Symbol;
5310
                Line upStreamLine = _upStreamObj as Line;
5311
                Symbol downStreamSymbol = _downStreamObj as Symbol;
5312
                Line downStreamLine = _downStreamObj as Line;
5313
                // 둘다 Line일 경우
5314
                if (upStreamLine != null && downStreamLine != null)
5315
                {
5316
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5317
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5318
                }
5319
                // 둘다 Symbol일 경우
5320
                else if (upStreamSymbol != null && downStreamSymbol != null)
5321
                {
5322
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
5323
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5324
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5325

    
5326
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5327
                    {
5328
                        if (connector.get_ItemStatus() != "Active")
5329
                            continue;
5330

    
5331
                        if (connector.Id != zeroLenthConnector.Id)
5332
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5333
                    }
5334

    
5335
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5336
                    {
5337
                        if (connector.get_ItemStatus() != "Active")
5338
                            continue;
5339

    
5340
                        if (connector.Id != zeroLenthConnector.Id)
5341
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5342
                    }
5343

    
5344
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5345
                    {
5346
                        if (connector.get_ItemStatus() != "Active")
5347
                            continue;
5348

    
5349
                        if (connector.Id != zeroLenthConnector.Id)
5350
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5351
                    }
5352

    
5353
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5354
                    {
5355
                        if (connector.get_ItemStatus() != "Active")
5356
                            continue;
5357

    
5358
                        if (connector.Id != zeroLenthConnector.Id)
5359
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5360
                    }
5361

    
5362
                    ReleaseCOMObjects(zeroLenthConnector);
5363
                    ReleaseCOMObjects(upStreamLMSymbol);
5364
                    ReleaseCOMObjects(downStreamLMSymbol);
5365
                }
5366
                else if (upStreamSymbol != null && downStreamLine != null)
5367
                {
5368
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
5369
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5370
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5371

    
5372
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5373
                    {
5374
                        if (connector.get_ItemStatus() != "Active")
5375
                            continue;
5376

    
5377
                        if (connector.Id == zeroLenthConnector.Id)
5378
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5379
                    }
5380

    
5381
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5382
                    {
5383
                        if (connector.get_ItemStatus() != "Active")
5384
                            continue;
5385

    
5386
                        if (connector.Id == zeroLenthConnector.Id)
5387
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5388
                    }
5389

    
5390
                    ReleaseCOMObjects(zeroLenthConnector);
5391
                    ReleaseCOMObjects(upStreamLMSymbol);
5392
                }
5393
                else if (upStreamLine != null && downStreamSymbol != null)
5394
                {
5395
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
5396
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5397
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5398

    
5399
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5400
                    {
5401
                        if (connector.get_ItemStatus() != "Active")
5402
                            continue;
5403

    
5404
                        if (connector.Id == zeroLenthConnector.Id)
5405
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5406
                    }
5407

    
5408
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5409
                    {
5410
                        if (connector.get_ItemStatus() != "Active")
5411
                            continue;
5412

    
5413
                        if (connector.Id == zeroLenthConnector.Id)
5414
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5415
                    }
5416

    
5417
                    ReleaseCOMObjects(zeroLenthConnector);
5418
                    ReleaseCOMObjects(downStreamLMSymbol);
5419
                }
5420
            }
5421

    
5422
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
5423
            {
5424
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5425
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5426
                {
5427
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5428
                    if (_LMAAttribute != null)
5429
                    {
5430
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5431
                            _LMAAttribute.set_Value(value);
5432
                        else if (_LMAAttribute.get_Value() != value)
5433
                            _LMAAttribute.set_Value(value);
5434
                    }
5435

    
5436
                    _LMModelItem.Commit();
5437
                }
5438
                if (_LMModelItem != null)
5439
                    ReleaseCOMObjects(_LMModelItem);
5440
            }
5441

    
5442
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
5443
            {
5444
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
5445
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5446
                {
5447
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5448
                    if (_LMAAttribute != null)
5449
                    {
5450
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5451
                            _LMAAttribute.set_Value(value);
5452
                        else if (_LMAAttribute.get_Value() != value)
5453
                            _LMAAttribute.set_Value(value);
5454
                    }
5455

    
5456
                    _LMModelItem.Commit();
5457
                }
5458
                if (_LMModelItem != null)
5459
                    ReleaseCOMObjects(_LMModelItem);
5460
            }
5461
            #endregion
5462
        }
5463

    
5464
        private void InputEndBreakAttribute(EndBreak endBreak)
5465
        {
5466
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5467
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5468

    
5469
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
5470
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
5471
            {
5472
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
5473
                if (labelPersist != null)
5474
                {
5475
                    LMRepresentation representation = labelPersist.RepresentationObject;
5476
                    if (representation != null)
5477
                    {
5478
                        LMConnector connector = dataSource.GetConnector(representation.Id);
5479
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
5480
                        string modelItemID = connector.ModelItemID;
5481
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
5482
                        {
5483
                            List<string> modelItemIDs = new List<string>();
5484
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5485
                            {
5486
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
5487
                                foreach (LMConnector item in symbol.Connect1Connectors)
5488
                                {
5489
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5490
                                        modelItemIDs.Add(item.ModelItemID);
5491
                                    ReleaseCOMObjects(item);
5492
                                }
5493
                                foreach (LMConnector item in symbol.Connect2Connectors)
5494
                                {
5495
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5496
                                        modelItemIDs.Add(item.ModelItemID);
5497
                                    ReleaseCOMObjects(item);
5498
                                }
5499
                                ReleaseCOMObjects(symbol);
5500
                                symbol = null;
5501
                            }
5502
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5503
                            {
5504
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
5505
                                foreach (LMConnector item in symbol.Connect1Connectors)
5506
                                {
5507
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5508
                                        modelItemIDs.Add(item.ModelItemID);
5509
                                    ReleaseCOMObjects(item);
5510
                                }
5511
                                foreach (LMConnector item in symbol.Connect2Connectors)
5512
                                {
5513
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5514
                                        modelItemIDs.Add(item.ModelItemID);
5515
                                    ReleaseCOMObjects(item);
5516
                                }
5517
                                ReleaseCOMObjects(symbol);
5518
                                symbol = null;
5519
                            }
5520

    
5521
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5522
                            if (modelItemIDs.Count == 1)
5523
                            {
5524
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5525
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5526
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5527
                                {
5528
                                    bool result = false;
5529
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5530
                                    {
5531
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5532
                                            result = true;
5533
                                        ReleaseCOMObjects(loop);
5534
                                    }
5535

    
5536
                                    if (result)
5537
                                    {
5538
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5539
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5540
                                        //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5541
                                        //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5542
                                        ZeroLengthModelItem.Commit();
5543
                                    }
5544
                                    else
5545
                                    {
5546
                                        List<string> loopModelItems = new List<string>();
5547
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5548
                                        {
5549
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5550
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5551
                                            {
5552
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5553
                                                    loopModelItems.Add(loop.ModelItemID);
5554
                                                ReleaseCOMObjects(loop);
5555
                                            }
5556
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5557
                                            {
5558
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5559
                                                    loopModelItems.Add(loop.ModelItemID);
5560
                                                ReleaseCOMObjects(loop);
5561
                                            }
5562
                                            ReleaseCOMObjects(_symbol);
5563
                                            _symbol = null;
5564
                                        }
5565
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5566
                                        {
5567
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5568
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5569
                                            {
5570
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5571
                                                    loopModelItems.Add(loop.ModelItemID);
5572
                                                ReleaseCOMObjects(loop);
5573
                                            }
5574
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5575
                                            {
5576
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5577
                                                    loopModelItems.Add(loop.ModelItemID);
5578
                                                ReleaseCOMObjects(loop);
5579
                                            }
5580
                                            ReleaseCOMObjects(_symbol);
5581
                                            _symbol = null;
5582
                                        }
5583

    
5584
                                        loopModelItems = loopModelItems.Distinct().ToList();
5585
                                        if (loopModelItems.Count == 1)
5586
                                        {
5587
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5588
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5589
                                            //object value2 = loopModelItem.Attributes["SubUnitNumber"].get_Value();
5590
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5591
                                            //modelItem.Attributes["SubUnitNumber"].set_Value(value2);
5592
                                            modelItem.Commit();
5593
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5594
                                            //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5595
                                            ZeroLengthModelItem.Commit();
5596

    
5597
                                            ReleaseCOMObjects(loopModelItem);
5598
                                            loopModelItem = null;
5599
                                        }
5600
                                    }
5601
                                }
5602
                                else
5603
                                {
5604
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5605
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5606
                                    //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5607
                                    //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5608
                                    ZeroLengthModelItem.Commit();
5609
                                }
5610
                                ReleaseCOMObjects(modelItem);
5611
                                modelItem = null;
5612
                                ReleaseCOMObjects(onlyOne);
5613
                                onlyOne = null;
5614
                            }
5615
                        }
5616
                        ReleaseCOMObjects(connector);
5617
                        connector = null;
5618
                        ReleaseCOMObjects(ZeroLengthModelItem);
5619
                        ZeroLengthModelItem = null;
5620
                    }
5621
                    ReleaseCOMObjects(representation);
5622
                    representation = null;
5623
                }
5624
                ReleaseCOMObjects(labelPersist);
5625
                labelPersist = null;
5626
            }
5627
        }
5628

    
5629
        /// <summary>
5630
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5631
        /// </summary>
5632
        /// <param name="text"></param>
5633
        private void NormalTextModeling(Text text)
5634
        {
5635
            LMSymbol _LMSymbol = null;
5636

    
5637
            LMItemNote _LMItemNote = null;
5638
            LMAAttribute _LMAAttribute = null;
5639

    
5640
            double x = 0;
5641
            double y = 0;
5642
            double angle = text.ANGLE;
5643
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5644

    
5645
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5646
            text.SPPID.SPPID_X = x;
5647
            text.SPPID.SPPID_Y = y;
5648

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

    
5664

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

    
5687
                        if (_LMAAttribute != null)
5688
                            ReleaseCOMObjects(_LMAAttribute);
5689
                        if (_LMItemNote != null)
5690
                            ReleaseCOMObjects(_LMItemNote);
5691
                    }
5692

    
5693
                    TextCorrectModeling(text);
5694
                }
5695
            }
5696
            if (_LMSymbol != null)
5697
                ReleaseCOMObjects(_LMSymbol);
5698
        }
5699

    
5700
        private void DefaultTextModeling(string value, double x, double y)
5701
        {
5702
            LMSymbol _LMSymbol = null;
5703

    
5704
            LMItemNote _LMItemNote = null;
5705
            LMAAttribute _LMAAttribute = null;
5706

    
5707
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5708
            if (_LMSymbol != null)
5709
            {
5710
                _LMSymbol.Commit();
5711
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5712
                if (_LMItemNote != null)
5713
                {
5714
                    _LMItemNote.Commit();
5715
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5716
                    if (_LMAAttribute != null)
5717
                    {
5718
                        _LMAAttribute.set_Value(value);
5719
                        _LMItemNote.Commit();
5720

    
5721
                        if (_LMAAttribute != null)
5722
                            ReleaseCOMObjects(_LMAAttribute);
5723
                        if (_LMItemNote != null)
5724
                            ReleaseCOMObjects(_LMItemNote);
5725
                    }
5726
                }
5727
            }
5728
            if (_LMSymbol != null)
5729
                ReleaseCOMObjects(_LMSymbol);
5730
        }
5731

    
5732
        private void AssociationTextModeling(Text text)
5733
        {
5734
            LMSymbol _LMSymbol = null;
5735
            LMConnector connectedLMConnector = null;
5736
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5737
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
5738
            {
5739
                Symbol symbol = owner as Symbol;
5740
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5741
                if (_LMSymbol != null)
5742
                {
5743
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5744
                    {
5745
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5746
                        {
5747
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5748

    
5749
                            if (mapping != null)
5750
                            {
5751
                                double x = 0;
5752
                                double y = 0;
5753

    
5754
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5755
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5756
                                Array array = new double[] { 0, x, y };
5757
                                text.SPPID.SPPID_X = x;
5758
                                text.SPPID.SPPID_Y = y;
5759
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5760
                                if (_LMLabelPersist != null)
5761
                                {
5762
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5763
                                    _LMLabelPersist.Commit();
5764
                                    ReleaseCOMObjects(_LMLabelPersist);
5765
                                }
5766
                            }
5767
                        }
5768
                    }
5769
                }
5770
            }
5771
            else if (owner != null && owner.GetType() == typeof(Line))
5772
            {
5773
                Line line = owner as Line;
5774
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5775
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5776

    
5777
                if (connectedLMConnector != null)
5778
                {
5779
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5780
                    {
5781
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5782
                        {
5783
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5784

    
5785
                            if (mapping != null)
5786
                            {
5787
                                double x = 0;
5788
                                double y = 0;
5789
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5790
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5791
                                Array array = new double[] { 0, x, y };
5792

    
5793
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5794
                                if (_LMLabelPersist != null)
5795
                                {
5796
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5797
                                    _LMLabelPersist.Commit();
5798

    
5799
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5800
                                    if (dependency != null)
5801
                                    {
5802
                                        radApp.ActiveSelectSet.RemoveAll();
5803
                                        radApp.ActiveSelectSet.Add(dependency);
5804
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
5805
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5806
                                        radApp.ActiveSelectSet.Transform(transform, true);
5807
                                        radApp.ActiveSelectSet.RemoveAll();
5808
                                    }
5809

    
5810
                                    ReleaseCOMObjects(_LMLabelPersist);
5811
                                }
5812
                            }
5813
                        }
5814
                    }
5815
                }
5816
            }
5817
            if (_LMSymbol != null)
5818
                ReleaseCOMObjects(_LMSymbol);
5819
        }
5820

    
5821
        private void TextCorrectModeling(Text text)
5822
        {
5823
            if (text.SPPID.Range == null)
5824
                return;
5825

    
5826
            bool needRemodeling = false;
5827
            bool loop = true;
5828
            GridSetting gridSetting = GridSetting.GetInstance();
5829
            while (loop)
5830
            {
5831
                loop = false;
5832
                foreach (var overlapText in document.TEXTINFOS)
5833
                {
5834
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5835
                        continue;
5836

    
5837
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5838
                    {
5839
                        double percentX = 0;
5840
                        double percentY = 0;
5841
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5842
                        {
5843
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5844
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5845
                        }
5846
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5847
                        {
5848
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5849
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5850
                        }
5851

    
5852
                        double tempX = 0;
5853
                        double tempY = 0;
5854
                        bool overlapX = false;
5855
                        bool overlapY = false;
5856
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5857
                        if (percentX >= percentY)
5858
                        {
5859
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5860
                            double move = gridSetting.Length * count;
5861
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5862
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5863
                            needRemodeling = true;
5864
                            loop = true;
5865
                        }
5866
                        else
5867
                        {
5868
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5869
                            double move = gridSetting.Length * count;
5870
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5871
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5872
                            needRemodeling = true;
5873
                            loop = true;
5874
                        }
5875
                    }
5876
                }
5877
            }
5878

    
5879

    
5880
            if (needRemodeling)
5881
            {
5882
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5883
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5884
                text.SPPID.RepresentationId = null;
5885

    
5886
                LMItemNote _LMItemNote = null;
5887
                LMAAttribute _LMAAttribute = null;
5888
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5889
                if (_LMSymbol != null)
5890
                {
5891
                    _LMSymbol.Commit();
5892
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5893
                    if (_LMItemNote != null)
5894
                    {
5895
                        _LMItemNote.Commit();
5896
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5897
                        if (_LMAAttribute != null)
5898
                        {
5899
                            _LMAAttribute.set_Value(text.VALUE);
5900
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5901
                            _LMItemNote.Commit();
5902

    
5903
                            ReleaseCOMObjects(_LMAAttribute);
5904
                            ReleaseCOMObjects(_LMItemNote);
5905
                        }
5906
                    }
5907
                }
5908

    
5909
                ReleaseCOMObjects(symbol);
5910
                symbol = null;
5911
                ReleaseCOMObjects(_LMItemNote);
5912
                _LMItemNote = null;
5913
                ReleaseCOMObjects(_LMAAttribute);
5914
                _LMAAttribute = null;
5915
                ReleaseCOMObjects(_LMSymbol);
5916
                _LMSymbol = null;
5917
            }
5918
        }
5919

    
5920
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5921
        {
5922
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5923
            {
5924
                List<Text> allTexts = new List<Text>();
5925
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5926
                LMRepresentation representation = targetLabel.RepresentationObject;
5927
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5928
                if (targetLabel.RepresentationObject != null && symbol != null)
5929
                {
5930
                    double[] symbolRange = null;
5931
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5932
                    if (symbolRange != null)
5933
                    {
5934
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5935
                        {
5936
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5937
                            if (findText != null)
5938
                            {
5939
                                double[] range = null;
5940
                                GetSPPIDSymbolRange(labelPersist, ref range);
5941
                                findText.SPPID.Range = range;
5942
                                allTexts.Add(findText);
5943
                            }
5944

    
5945
                            ReleaseCOMObjects(labelPersist);
5946
                        }
5947

    
5948
                        if (allTexts.Count > 0)
5949
                        {
5950
                            #region Sort Text By Y
5951
                            allTexts.Sort(SortTextByY);
5952
                            int SortTextByY(Text a, Text b)
5953
                            {
5954
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5955
                            }
5956
                            #endregion
5957

    
5958
                            #region 정렬하기전 방향
5959
                            List<Text> left = new List<Text>();
5960
                            List<Text> down = new List<Text>();
5961
                            List<Text> right = new List<Text>();
5962
                            List<Text> up = new List<Text>();
5963
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5964
                            foreach (var loopText in allTexts)
5965
                            {
5966
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5967
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5968
                                double originX = 0;
5969
                                double originY = 0;
5970
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5971
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5972

    
5973
                                if (angle < 45)
5974
                                {
5975
                                    // Text 오른쪽
5976
                                    if (textCenterX > originX)
5977
                                        right.Add(loopText);
5978
                                    // Text 왼쪽
5979
                                    else
5980
                                        left.Add(loopText);
5981
                                }
5982
                                else
5983
                                {
5984
                                    // Text 아래쪽
5985
                                    if (textCenterY > originY)
5986
                                        down.Add(loopText);
5987
                                    // Text 위쪽
5988
                                    else
5989
                                        up.Add(loopText);
5990
                                }
5991
                            }
5992

    
5993
                            #endregion
5994

    
5995
                            foreach (var texts in sortTexts)
5996
                            {
5997
                                if (texts.Count == 0)
5998
                                    continue;
5999

    
6000
                                #region 첫번째 Text로 기준 맞춤
6001
                                for (int i = 0; i < texts.Count; i++)
6002
                                {
6003
                                    if (i != 0)
6004
                                    {
6005
                                        Text currentText = texts[i];
6006
                                        Text prevText = texts[i - 1];
6007
                                        double minY = prevText.SPPID.Range[1];
6008
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
6009
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
6010
                                        double _gapX = centerX - centerPrevX;
6011
                                        double _gapY = currentText.SPPID.Range[3] - minY;
6012
                                        MoveText(currentText, _gapX, _gapY);
6013
                                    }
6014
                                }
6015
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
6016
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
6017
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
6018
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
6019
                                rangeMinX.Sort();
6020
                                rangeMinY.Sort();
6021
                                rangeMaxX.Sort();
6022
                                rangeMaxY.Sort();
6023
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
6024
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
6025
                                #endregion
6026
                                #region 정렬
6027
                                Text correctBySymbol = texts[0];
6028
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
6029
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
6030
                                double originX = 0;
6031
                                double originY = 0;
6032
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6033
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6034
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
6035
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
6036

    
6037
                                double gapX = 0;
6038
                                double gapY = 0;
6039
                                if (angle < 45)
6040
                                {
6041
                                    // Text 오른쪽
6042
                                    if (textCenterX > originX)
6043
                                    {
6044
                                        gapX = rangeMinX[0] - symbolRange[2];
6045
                                        gapY = allTextCenterY - symbolCenterY;
6046
                                    }
6047
                                    // Text 왼쪽
6048
                                    else
6049
                                    {
6050
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
6051
                                        gapY = allTextCenterY - symbolCenterY;
6052
                                    }
6053
                                }
6054
                                else
6055
                                {
6056
                                    // Text 아래쪽
6057
                                    if (textCenterY > originY)
6058
                                    {
6059
                                        gapX = allTextCenterX - symbolCenterX;
6060
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
6061
                                    }
6062
                                    // Text 위쪽
6063
                                    else
6064
                                    {
6065
                                        gapX = allTextCenterX - symbolCenterX;
6066
                                        gapY = rangeMinY[0] - symbolRange[3];
6067
                                    }
6068
                                }
6069

    
6070
                                foreach (var item in texts)
6071
                                {
6072
                                    MoveText(item, gapX, gapY);
6073
                                    RemodelingAssociationText(item);
6074
                                }
6075
                                #endregion
6076
                            }
6077
                        }
6078
                    }
6079
                }
6080

    
6081
                void MoveText(Text moveText, double x, double y)
6082
                {
6083
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
6084
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
6085
                    moveText.SPPID.Range = new double[] {
6086
                        moveText.SPPID.Range[0] - x,
6087
                        moveText.SPPID.Range[1]- y,
6088
                        moveText.SPPID.Range[2]- x,
6089
                        moveText.SPPID.Range[3]- y
6090
                    };
6091
                }
6092

    
6093
                endTexts.AddRange(allTexts);
6094

    
6095
                ReleaseCOMObjects(targetLabel);
6096
                targetLabel = null;
6097
                ReleaseCOMObjects(representation);
6098
                representation = null;
6099
            }
6100
        }
6101

    
6102
        private void RemodelingAssociationText(Text text)
6103
        {
6104
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6105
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
6106
            removeLabel.Commit();
6107
            ReleaseCOMObjects(removeLabel);
6108
            removeLabel = null;
6109

    
6110
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6111
            if (owner != null && owner.GetType() == typeof(Symbol))
6112
            {
6113
                Symbol symbol = owner as Symbol;
6114
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6115
                if (_LMSymbol != null)
6116
                {
6117
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
6118
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6119
                    {
6120
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6121

    
6122
                        if (mapping != null)
6123
                        {
6124
                            double x = 0;
6125
                            double y = 0;
6126

    
6127
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
6128
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6129
                            if (_LMLabelPersist != null)
6130
                            {
6131
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6132
                                _LMLabelPersist.Commit();
6133
                            }
6134
                            ReleaseCOMObjects(_LMLabelPersist);
6135
                            _LMLabelPersist = null;
6136
                        }
6137
                    }
6138
                }
6139
                ReleaseCOMObjects(_LMSymbol);
6140
                _LMSymbol = null;
6141
            }
6142
        }
6143

    
6144
        /// <summary>
6145
        /// Note Modeling
6146
        /// </summary>
6147
        /// <param name="note"></param>
6148
        private void NoteModeling(Note note, List<Note> correctList)
6149
        {
6150
            LMSymbol _LMSymbol = null;
6151
            LMItemNote _LMItemNote = null;
6152
            LMAAttribute _LMAAttribute = null;
6153

    
6154
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
6155
            {
6156
                double x = 0;
6157
                double y = 0;
6158

    
6159
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
6160
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6161
                note.SPPID.SPPID_X = x;
6162
                note.SPPID.SPPID_Y = y;
6163

    
6164
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
6165
                if (_LMSymbol != null)
6166
                {
6167
                    _LMSymbol.Commit();
6168
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6169
                    if (_LMItemNote != null)
6170
                    {
6171
                        _LMItemNote.Commit();
6172
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6173
                        if (_LMAAttribute != null)
6174
                        {
6175
                            _LMAAttribute.set_Value(note.VALUE);
6176
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6177

    
6178
                            double[] range = null;
6179
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6180
                            {
6181
                                double[] temp = null;
6182
                                GetSPPIDSymbolRange(labelPersist, ref temp);
6183
                                if (temp != null)
6184
                                {
6185
                                    if (range == null)
6186
                                        range = temp;
6187
                                    else
6188
                                    {
6189
                                        range = new double[] {
6190
                                            Math.Min(range[0], temp[0]),
6191
                                            Math.Min(range[1], temp[1]),
6192
                                            Math.Max(range[2], temp[2]),
6193
                                            Math.Max(range[3], temp[3])
6194
                                        };
6195
                                    }
6196
                                }
6197
                            }
6198
                            if (range != null)
6199
                                correctList.Add(note);
6200
                            note.SPPID.Range = range;
6201

    
6202

    
6203
                            _LMItemNote.Commit();
6204
                        }
6205
                    }
6206
                }
6207
            }
6208

    
6209
            if (_LMAAttribute != null)
6210
                ReleaseCOMObjects(_LMAAttribute);
6211
            if (_LMItemNote != null)
6212
                ReleaseCOMObjects(_LMItemNote);
6213
            if (_LMSymbol != null)
6214
                ReleaseCOMObjects(_LMSymbol);
6215
        }
6216

    
6217
        private void NoteCorrectModeling(Note note, List<Note> endList)
6218
        {
6219
            bool needRemodeling = false;
6220
            bool loop = true;
6221
            GridSetting gridSetting = GridSetting.GetInstance();
6222
            while (loop)
6223
            {
6224
                loop = false;
6225
                foreach (var overlap in endList)
6226
                {
6227
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
6228
                    {
6229
                        double tempX = 0;
6230
                        double tempY = 0;
6231
                        bool overlapX = false;
6232
                        bool overlapY = false;
6233
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6234
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
6235
                        if (overlapY && angle >= 45)
6236
                        {
6237
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6238
                            double move = gridSetting.Length * count;
6239
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
6240
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
6241
                            needRemodeling = true;
6242
                            loop = true;
6243
                        }
6244
                        if (overlapX && angle <= 45)
6245
                        {
6246
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6247
                            double move = gridSetting.Length * count;
6248
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
6249
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
6250
                            needRemodeling = true;
6251
                            loop = true;
6252
                        }
6253
                    }
6254
                }
6255
            }
6256

    
6257

    
6258
            if (needRemodeling)
6259
            {
6260
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
6261
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6262
                note.SPPID.RepresentationId = null;
6263

    
6264
                LMItemNote _LMItemNote = null;
6265
                LMAAttribute _LMAAttribute = null;
6266
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
6267
                if (_LMSymbol != null)
6268
                {
6269
                    _LMSymbol.Commit();
6270
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6271
                    if (_LMItemNote != null)
6272
                    {
6273
                        _LMItemNote.Commit();
6274
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6275
                        if (_LMAAttribute != null)
6276
                        {
6277
                            _LMAAttribute.set_Value(note.VALUE);
6278
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6279
                            _LMItemNote.Commit();
6280

    
6281
                            ReleaseCOMObjects(_LMAAttribute);
6282
                            ReleaseCOMObjects(_LMItemNote);
6283
                        }
6284
                    }
6285
                }
6286

    
6287
                ReleaseCOMObjects(symbol);
6288
                symbol = null;
6289
                ReleaseCOMObjects(_LMItemNote);
6290
                _LMItemNote = null;
6291
                ReleaseCOMObjects(_LMAAttribute);
6292
                _LMAAttribute = null;
6293
                ReleaseCOMObjects(_LMSymbol);
6294
                _LMSymbol = null;
6295
            }
6296

    
6297
            endList.Add(note);
6298
        }
6299

    
6300
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
6301
        {
6302
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6303
            if (modelItem != null)
6304
            {
6305
                foreach (LMRepresentation rep in modelItem.Representations)
6306
                {
6307
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
6308
                    {
6309
                        LMConnector connector = dataSource.GetConnector(rep.Id);
6310
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
6311
                        {
6312
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
6313
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6314
                            if (modelItemIds.Count == 1)
6315
                            {
6316
                                string joinModelItemId = modelItemIds[0];
6317
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6318
                                if (survivorId != null)
6319
                                    break;
6320
                            }
6321
                        }
6322
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
6323
                        {
6324
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
6325
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6326
                            if (modelItemIds.Count == 1)
6327
                            {
6328
                                string joinModelItemId = modelItemIds[0];
6329
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6330
                                if (survivorId != null)
6331
                                    break;
6332
                            }
6333
                        }
6334
                    }
6335
                }
6336
            }
6337
        }
6338

    
6339
        /// <summary>
6340
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
6341
        /// </summary>
6342
        /// <param name="x"></param>
6343
        /// <param name="y"></param>
6344
        /// <param name="originX"></param>
6345
        /// <param name="originY"></param>
6346
        /// <param name="SPPIDLabelLocation"></param>
6347
        /// <param name="location"></param>
6348
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
6349
        {
6350
            if (location == Location.None)
6351
            {
6352
                x = originX;
6353
                y = originY;
6354
            }
6355
            else
6356
            {
6357
                if (location.HasFlag(Location.Center))
6358
                {
6359
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
6360
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
6361
                }
6362

    
6363
                if (location.HasFlag(Location.Left))
6364
                    x = SPPIDLabelLocation.X1;
6365
                else if (location.HasFlag(Location.Right))
6366
                    x = SPPIDLabelLocation.X2;
6367

    
6368
                if (location.HasFlag(Location.Down))
6369
                    y = SPPIDLabelLocation.Y1;
6370
                else if (location.HasFlag(Location.Up))
6371
                    y = SPPIDLabelLocation.Y2;
6372
            }
6373
        }
6374

    
6375
        /// <summary>
6376
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
6377
        /// 1. Angle Valve
6378
        /// 2. 3개로 이루어진 Symbol Group
6379
        /// </summary>
6380
        /// <returns></returns>
6381
        private List<Symbol> GetPrioritySymbol()
6382
        {
6383
            DataTable symbolTable = document.SymbolTable;
6384
            // List에 순서대로 쌓는다.
6385
            List<Symbol> symbols = new List<Symbol>();
6386

    
6387
            // Angle Valve 부터
6388
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
6389
            {
6390
                if (!symbols.Contains(symbol))
6391
                {
6392
                    double originX = 0;
6393
                    double originY = 0;
6394

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

    
6399
                    SlopeType slopeType1 = SlopeType.None;
6400
                    SlopeType slopeType2 = SlopeType.None;
6401
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
6402
                    {
6403
                        double connectorX = 0;
6404
                        double connectorY = 0;
6405
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
6406
                        if (slopeType1 == SlopeType.None)
6407
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6408
                        else
6409
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6410
                    }
6411

    
6412
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
6413
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
6414
                        symbols.Add(symbol);
6415
                }
6416
            }
6417

    
6418
            List<Symbol> tempSymbols = new List<Symbol>();
6419
            // Conn 갯수 기준
6420
            foreach (var item in document.SYMBOLS)
6421
            {
6422
                if (!symbols.Contains(item))
6423
                    tempSymbols.Add(item);
6424
            }
6425
            tempSymbols.Sort(SortSymbolPriority);
6426
            symbols.AddRange(tempSymbols);
6427

    
6428
            return symbols;
6429
        }
6430

    
6431
        private void SetPriorityLine(List<Line> lines)
6432
        {
6433
            lines.Sort(SortLinePriority);
6434

    
6435
            int SortLinePriority(Line a, Line b)
6436
            {
6437
                // Branch 없는것부터
6438
                int branchRetval = CompareBranchLine(a, b);
6439
                if (branchRetval != 0)
6440
                {
6441
                    return branchRetval;
6442
                }
6443
                else
6444
                {
6445
                    // Symbol 연결 갯수
6446
                    int connSymbolRetval = CompareConnSymbol(a, b);
6447
                    if (connSymbolRetval != 0)
6448
                    {
6449
                        return connSymbolRetval;
6450
                    }
6451
                    else
6452
                    {
6453
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
6454
                        int connItemRetval = CompareConnItem(a, b);
6455
                        if (connItemRetval != 0)
6456
                        {
6457
                            return connItemRetval;
6458
                        }
6459
                        else
6460
                        {
6461
                            // ConnectedItem이 없는것
6462
                            int noneConnRetval = CompareNoneConn(a, b);
6463
                            if (noneConnRetval != 0)
6464
                            {
6465
                                return noneConnRetval;
6466
                            }
6467
                            else
6468
                            {
6469

    
6470
                            }
6471
                        }
6472
                    }
6473
                }
6474

    
6475
                return 0;
6476
            }
6477

    
6478
            int CompareNotSegmentLine(Line a, Line b)
6479
            {
6480
                List<Connector> connectorsA = a.CONNECTORS
6481
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6482
                    .ToList();
6483

    
6484
                List<Connector> connectorsB = b.CONNECTORS
6485
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6486
                    .ToList();
6487

    
6488
                // 오름차순
6489
                return connectorsB.Count.CompareTo(connectorsA.Count);
6490
            }
6491

    
6492
            int CompareConnSymbol(Line a, Line b)
6493
            {
6494
                List<Connector> connectorsA = a.CONNECTORS
6495
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6496
                    .ToList();
6497

    
6498
                List<Connector> connectorsB = b.CONNECTORS
6499
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6500
                    .ToList();
6501

    
6502
                // 오름차순
6503
                return connectorsB.Count.CompareTo(connectorsA.Count);
6504
            }
6505

    
6506
            int CompareConnItem(Line a, Line b)
6507
            {
6508
                List<Connector> connectorsA = a.CONNECTORS
6509
                    .Where(conn => conn.ConnectedObject != null &&
6510
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6511
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6512
                    .ToList();
6513

    
6514
                List<Connector> connectorsB = b.CONNECTORS
6515
                    .Where(conn => conn.ConnectedObject != null &&
6516
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6517
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6518
                    .ToList();
6519

    
6520
                // 오름차순
6521
                return connectorsB.Count.CompareTo(connectorsA.Count);
6522
            }
6523

    
6524
            int CompareBranchLine(Line a, Line b)
6525
            {
6526
                List<Connector> connectorsA = a.CONNECTORS
6527
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6528
                    .ToList();
6529
                List<Connector> connectorsB = b.CONNECTORS
6530
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6531
                    .ToList();
6532

    
6533
                // 내림차순
6534
                return connectorsA.Count.CompareTo(connectorsB.Count);
6535
            }
6536

    
6537
            int CompareNoneConn(Line a, Line b)
6538
            {
6539
                List<Connector> connectorsA = a.CONNECTORS
6540
                    .Where(conn => conn.ConnectedObject == null)
6541
                    .ToList();
6542

    
6543
                List<Connector> connectorsB = b.CONNECTORS
6544
                    .Where(conn => conn.ConnectedObject == null)
6545
                    .ToList();
6546

    
6547
                // 오름차순
6548
                return connectorsB.Count.CompareTo(connectorsA.Count);
6549
            }
6550
        }
6551

    
6552
        private void SortText(List<Text> texts)
6553
        {
6554
            texts.Sort(Sort);
6555

    
6556
            int Sort(Text a, Text b)
6557
            {
6558
                int yRetval = CompareY(a, b);
6559
                if (yRetval != 0)
6560
                {
6561
                    return yRetval;
6562
                }
6563
                else
6564
                {
6565
                    return CompareX(a, b);
6566
                }
6567
            }
6568

    
6569
            int CompareY(Text a, Text b)
6570
            {
6571
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6572
            }
6573

    
6574
            int CompareX(Text a, Text b)
6575
            {
6576
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6577
            }
6578
        }
6579
        private void SortNote(List<Note> notes)
6580
        {
6581
            notes.Sort(Sort);
6582

    
6583
            int Sort(Note a, Note b)
6584
            {
6585
                int yRetval = CompareY(a, b);
6586
                if (yRetval != 0)
6587
                {
6588
                    return yRetval;
6589
                }
6590
                else
6591
                {
6592
                    return CompareX(a, b);
6593
                }
6594
            }
6595

    
6596
            int CompareY(Note a, Note b)
6597
            {
6598
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6599
            }
6600

    
6601
            int CompareX(Note a, Note b)
6602
            {
6603
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6604
            }
6605
        }
6606

    
6607
        private void SortBranchLines()
6608
        {
6609
            BranchLines.Sort(SortBranchLine);
6610
            int SortBranchLine(Line a, Line b)
6611
            {
6612
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6613
                 x.ConnectedObject.GetType() == typeof(Line) &&
6614
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6615
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6616

    
6617
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6618
                 x.ConnectedObject.GetType() == typeof(Line) &&
6619
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6620
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6621

    
6622
                // 내림차순
6623
                return countA.CompareTo(countB);
6624
            }
6625
        }
6626

    
6627
        private static int SortSymbolPriority(Symbol a, Symbol b)
6628
        {
6629
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6630
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6631
            int retval = countB.CompareTo(countA);
6632
            if (retval != 0)
6633
                return retval;
6634
            else
6635
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6636
        }
6637

    
6638
        private string GetSPPIDFileName(LMModelItem modelItem)
6639
        {
6640
            string symbolPath = null;
6641
            foreach (LMRepresentation rep in modelItem.Representations)
6642
            {
6643
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6644
                {
6645
                    symbolPath = rep.get_FileName();
6646
                    break;
6647
                }
6648
            }
6649
            return symbolPath;
6650
        }
6651

    
6652
        private string GetSPPIDFileName(string modelItemId)
6653
        {
6654
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6655
            string symbolPath = null;
6656
            foreach (LMRepresentation rep in modelItem.Representations)
6657
            {
6658
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6659
                {
6660
                    symbolPath = rep.get_FileName();
6661
                    break;
6662
                }
6663
            }
6664
            ReleaseCOMObjects(modelItem);
6665
            return symbolPath;
6666
        }
6667

    
6668
        /// <summary>
6669
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6670
        /// </summary>
6671
        /// <param name="graphicOID"></param>
6672
        /// <param name="milliseconds"></param>
6673
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6674
        {
6675
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6676
            {
6677
                double minX = 0;
6678
                double minY = 0;
6679
                double maxX = 0;
6680
                double maxY = 0;
6681
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6682
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6683

    
6684
                Thread.Sleep(milliseconds);
6685
            }
6686
        }
6687

    
6688
        /// <summary>
6689
        /// ComObject를 Release
6690
        /// </summary>
6691
        /// <param name="objVars"></param>
6692
        public void ReleaseCOMObjects(params object[] objVars)
6693
        {
6694
            if (objVars != null)
6695
            {
6696
                int intNewRefCount = 0;
6697
                foreach (object obj in objVars)
6698
                {
6699
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6700
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6701
                }
6702
            }
6703
        }
6704

    
6705
        /// IDisposable 구현
6706
        ~AutoModeling()
6707
        {
6708
            this.Dispose(false);
6709
        }
6710

    
6711
        private bool disposed;
6712
        public void Dispose()
6713
        {
6714
            this.Dispose(true);
6715
            GC.SuppressFinalize(this);
6716
        }
6717

    
6718
        protected virtual void Dispose(bool disposing)
6719
        {
6720
            if (this.disposed) return;
6721
            if (disposing)
6722
            {
6723
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6724
            }
6725
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6726
            this.disposed = true;
6727
        }
6728
    }
6729
}
클립보드 이미지 추가 (최대 크기: 500 MB)