프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ a9f6ef3c

이력 | 보기 | 이력해설 | 다운로드 (333 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
using System.IO;
26

    
27
namespace Converter.SPPID
28
{
29
    [Flags]
30
    public enum SegmentLocation
31
    {
32
        None = 0,
33
        Right = 1,
34
        Left = 2,
35
        Down = 4,
36
        Up = 8
37
    }
38
    public class AutoModeling : IDisposable
39
    {
40
        Placement _placement;
41
        LMADataSource dataSource;
42
        string drawingID;
43
        dynamic newDrawing;
44
        dynamic application;
45
        bool closeDocument;
46
        Ingr.RAD2D.Application radApp;
47
        SPPID_Document document;
48
        ETCSetting _ETCSetting;
49
        DataTable nominalDiameterTable = null;
50
        public string DocumentLabelText { get; set; }
51

    
52
        List<double[]> itemRange = new List<double[]>();
53

    
54
        List<Line> BranchLines = new List<Line>();
55
        List<string> ZeroLengthSymbolToSymbolModelItemID = 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
                radApp.Interactive = false;
96

    
97
                nominalDiameterTable = Project_DB.SelectProjectNominalDiameter();
98
                _placement = new Placement();
99
                dataSource = _placement.PIDDataSource;
100

    
101
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
102
                {
103
                    Log.Write("Start Modeling");
104
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
105
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
106
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 26);
107
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
108

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

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

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

    
201
                Project_DB.InsertDrawingInfoAndOPCInfo(document.PATH, drawingNumber, drawingName, document);
202
                //Project_DB.InsertLineNumberInfo(document.PATH, drawingNumber, drawingName, document);
203

    
204
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
205
                {
206
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
207
                    SplashScreenManager.CloseForm(false);
208
                    Log.Write("\r\n");
209
                }
210
                Thread.Sleep(1000);
211

    
212
                Log.Write("End Modeling");
213
                radApp.ActiveWindow.Fit();
214

    
215
                ReleaseCOMObjects(application);
216
                application = null;
217
                if (radApp.ActiveDocument != null)
218
                {
219
                    if (newDrawing != null)
220
                    {
221
                        newDrawing.Save();
222
                        if (closeDocument)
223
                            newDrawing.CloseDrawing(true);
224
                        ReleaseCOMObjects(newDrawing);
225
                        newDrawing = null;
226
                    }
227
                    else if (newDrawing == null)
228
                    {
229
                        Log.Write("error document");
230
                    }
231
                }
232

    
233
                ReleaseCOMObjects(dataSource);
234
                dataSource = null;
235
                ReleaseCOMObjects(_placement);
236
                _placement = null;
237

    
238
                Thread.Sleep(1000);
239
            }
240
        }
241

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

    
317
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
318
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
319

    
320
            SetPriorityLine(step1_Line);
321
            while (step1_Line.Count > 0)
322
            {
323
                try
324
                {
325
                    Line item = step1_Line[0];
326
                    if (!string.IsNullOrEmpty(item.SPPID.ModelItemId) || BranchLines.Contains(item) || document.VentDrainLine.Contains(item))
327
                    {
328
                        step1_Line.Remove(item);
329
                    }
330
                    else
331
                    {
332
                        NewLineModeling(item);
333
                        step1_Line.Remove(item);
334
                        if (string.IsNullOrEmpty(item.SPPID.ModelItemId))
335
                        {
336
                            step1_Line.Add(item);
337
                        }
338
                    }
339
                    if (!step1_Line.Contains(item))
340
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
341
                }
342
                catch (Exception ex)
343
                {
344
                    Log.Write("Error in NewLineModeling");
345
                    Log.Write("UID : " + step1_Line[0].UID);
346
                    Log.Write(ex.Message);
347
                    Log.Write(ex.StackTrace);
348
                    step1_Line.Remove(step1_Line[0]);
349
                }
350
            }
351

    
352
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
353
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
354
            int branchCount = BranchLines.Count;
355
            SortBranchLines();
356
            while (BranchLines.Count > 0)
357
            {
358
                try
359
                {   
360
                    Line item = BranchLines[0];
361
                    if (!string.IsNullOrEmpty(item.SPPID.ModelItemId) || document.VentDrainLine.Contains(item))
362
                    {
363
                        BranchLines.Remove(item);
364
                    }
365
                    else
366
                    { 
367
                        NewLineModeling(item, true);
368
                        BranchLines.Remove(item);
369
                        if (string.IsNullOrEmpty(item.SPPID.ModelItemId))
370
                        {
371
                            BranchLines.Add(item);
372
                        }
373
                    }
374
                    if (!BranchLines.Contains(item))
375
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
376
                }
377
                catch (Exception ex)
378
                {
379
                    Log.Write("Error in NewLineModeling");
380
                    Log.Write("UID : " + BranchLines[0].UID);
381
                    Log.Write(ex.Message);
382
                    Log.Write(ex.StackTrace);
383
                    BranchLines.Remove(BranchLines[0]);
384
                }
385
            }
386

    
387
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
388
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
389
            while (stepLast_Line.Count > 0)
390
            {
391
                try
392
                {
393
                    Line item = stepLast_Line[0];
394
                    if (!string.IsNullOrEmpty(item.SPPID.ModelItemId) || BranchLines.Contains(item) || document.VentDrainLine.Contains(item))
395
                    {
396
                        stepLast_Line.Remove(item);
397
                    }
398
                    else
399
                    {
400
                        NewLineModeling(item);
401
                        stepLast_Line.Remove(item);
402
                        if (string.IsNullOrEmpty(item.SPPID.ModelItemId))
403
                        {
404
                            stepLast_Line.Add(item);
405
                        }
406
                    }
407
                    if (!stepLast_Line.Contains(item))
408
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
409
                }
410
                catch (Exception ex)
411
                {
412
                    Log.Write("Error in NewLineModeling");
413
                    Log.Write("UID : " + stepLast_Line[0].UID);
414
                    Log.Write(ex.Message);
415
                    Log.Write(ex.StackTrace);
416
                    stepLast_Line.Remove(stepLast_Line[0]);
417
                }
418
            }
419
        }
420
        private void RunVentDrainModeling()
421
        {
422
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VentDrainLine.Count);
423
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Vent Drain Modeling");
424
            foreach (var item in document.VentDrainLine)
425
            {
426
                try
427
                {
428
                    Connector connector = item.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
429
                    if (connector != null)
430
                    {
431
                        SetCoordinate();
432
                        Symbol connSymbol = connector.ConnectedObject as Symbol;
433
                        SymbolModeling(connSymbol, null);
434
                        NewLineModeling(item, true);
435

    
436
                        GridSetting grid = GridSetting.GetInstance();
437
                        int count = grid.DrainValveCellCount;
438
                        double length = grid.Length;
439

    
440
                        // 길이 확인
441
                        if (!string.IsNullOrEmpty(item.SPPID.ModelItemId))
442
                        {
443
                            LMConnector _LMConnector = GetLMConnectorOnlyOne(item.SPPID.ModelItemId);
444
                            if (_LMConnector != null)
445
                            {
446
                                double[] connectorRange = GetConnectorRange(_LMConnector);
447
                                double connectorLength = double.NaN;
448
                                if (item.SlopeType == SlopeType.HORIZONTAL)
449
                                    connectorLength = connectorRange[2] - connectorRange[0];
450
                                else if (item.SlopeType == SlopeType.VERTICAL)
451
                                    connectorLength = connectorRange[3] - connectorRange[1];
452

    
453
                                if (!double.IsNaN(connectorLength) && connectorLength != count * length)
454
                                {
455
                                    double move = count * length - connectorLength;
456
                                    List<Symbol> group = new List<Symbol>();
457
                                    SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
458
                                    foreach (var symbol in group)
459
                                    {
460
                                        int connSymbolIndex = item.CONNECTORS.IndexOf(item.CONNECTORS.Find(x => x.ConnectedObject == connSymbol));
461
                                        if (item.SlopeType == SlopeType.HORIZONTAL)
462
                                        {
463
                                            if (connSymbolIndex == 0)
464
                                            {
465
                                                if (item.SPPID.START_X > item.SPPID.END_X)
466
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
467
                                                else
468
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
469
                                            }
470
                                            else
471
                                            {
472
                                                if (item.SPPID.START_X < item.SPPID.END_X)
473
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
474
                                                else
475
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
476
                                            }
477
                                        }
478
                                        else if (item.SlopeType == SlopeType.VERTICAL)
479
                                        {
480
                                            if (connSymbolIndex == 0)
481
                                            {
482
                                                if (item.SPPID.START_Y > item.SPPID.END_Y)
483
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
484
                                                else
485
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
486
                                            }
487
                                            else
488
                                            {
489
                                                if (item.SPPID.START_Y < item.SPPID.END_Y)
490
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
491
                                                else
492
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
493
                                            }
494
                                        }
495
                                    }
496

    
497
                                    // 제거
498
                                    RemoveSymbol(connSymbol);
499
                                    RemoveLine(item);
500

    
501
                                    // 재생성
502
                                    SymbolModelingBySymbol(connSymbol);
503
                                    NewLineModeling(item, true);
504
                                }
505
                            }
506

    
507
                            ReleaseCOMObjects(_LMConnector);
508
                            _LMConnector = null;
509
                        }
510
                    }
511
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
512
                }
513
                catch (Exception ex)
514
                {
515
                    Log.Write("Error in NewLineModeling");
516
                    Log.Write("UID : " + item.UID);
517
                    Log.Write(ex.Message);
518
                    Log.Write(ex.StackTrace);
519
                }
520

    
521
                void SetCoordinate()
522
                {
523
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
524
                    if (branchConnector != null)
525
                    {
526
                        Line connLine = branchConnector.ConnectedObject as Line;
527
                        double x = 0;
528
                        double y = 0;
529
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
530
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
531
                        if (targetConnector != null)
532
                        {
533
                            List<Symbol> group = new List<Symbol>();
534
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
535
                            if (item.SlopeType == SlopeType.HORIZONTAL)
536
                            {
537
                                item.SPPID.START_Y = y;
538
                                item.SPPID.END_Y = y;
539
                                foreach (var symbol in group)
540
                                {
541
                                    symbol.SPPID.ORIGINAL_Y = y;
542
                                    symbol.SPPID.SPPID_Y = y;
543
                                }
544
                            }
545
                            else if (item.SlopeType == SlopeType.VERTICAL)
546
                            {
547
                                item.SPPID.START_X = x;
548
                                item.SPPID.END_X = x;
549
                                foreach (var symbol in group)
550
                                {
551
                                    symbol.SPPID.ORIGINAL_X = x;
552
                                    symbol.SPPID.SPPID_X = x;
553
                                }
554
                            }
555
                        }
556
                        ReleaseCOMObjects(targetConnector);
557
                        targetConnector = null;
558
                    }
559
                }
560
            }
561
        }
562
        private void RunClearNominalDiameter()
563
        {
564
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
565
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
566
            return;
567

    
568
            List<string> endClearModelItemID = new List<string>();
569
            for (int i = 0; i < document.LINES.Count; i++)
570
            {
571
                Line item = document.LINES[i];
572
                string modelItemID = item.SPPID.ModelItemId;
573
                if (!string.IsNullOrEmpty(modelItemID))
574
                {
575
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
576
                    if (modelItem != null)
577
                    {
578
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
579
                        if (attribute != null)
580
                            attribute.set_Value(DBNull.Value);
581

    
582
                        modelItem.Commit();
583
                        ReleaseCOMObjects(modelItem);
584
                        modelItem = null;
585
                    }
586
                }
587
                if (!endClearModelItemID.Contains(modelItemID))
588
                    endClearModelItemID.Add(modelItemID);
589
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
590
            }
591
            for (int i = 0; i < document.SYMBOLS.Count; i++)
592
            {
593
                Symbol item = document.SYMBOLS[i];
594
                string repID = item.SPPID.RepresentationId;
595
                string modelItemID = item.SPPID.ModelItemID;
596
                if (!string.IsNullOrEmpty(modelItemID))
597
                {
598
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
599
                    if (modelItem != null)
600
                    {
601
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
602
                        if (attribute != null)
603
                            attribute.set_Value(DBNull.Value);
604
                        int index = 1;
605
                        while (true)
606
                        {
607
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
608
                            if (attribute != null)
609
                                attribute.set_Value(DBNull.Value);
610
                            else
611
                                break;
612
                            index++;
613
                        }
614
                        modelItem.Commit();
615
                        ReleaseCOMObjects(modelItem);
616
                        modelItem = null;
617
                    }
618
                }
619
                if (!string.IsNullOrEmpty(repID))
620
                {
621
                    LMSymbol symbol = dataSource.GetSymbol(repID);
622
                    if (symbol != null)
623
                    {
624
                        foreach (LMConnector connector in symbol.Connect1Connectors)
625
                        {
626
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
627
                            {
628
                                endClearModelItemID.Add(connector.ModelItemID);
629
                                LMModelItem modelItem = connector.ModelItemObject;
630
                                if (modelItem != null)
631
                                {
632
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
633
                                    if (attribute != null)
634
                                        attribute.set_Value(DBNull.Value);
635

    
636
                                    modelItem.Commit();
637
                                    ReleaseCOMObjects(modelItem);
638
                                    modelItem = null;
639
                                }
640
                            }
641
                        }
642
                        foreach (LMConnector connector in symbol.Connect2Connectors)
643
                        {
644
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
645
                            {
646
                                endClearModelItemID.Add(connector.ModelItemID);
647
                                LMModelItem modelItem = connector.ModelItemObject;
648
                                if (modelItem != null)
649
                                {
650
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
651
                                    if (attribute != null)
652
                                        attribute.set_Value(DBNull.Value);
653

    
654
                                    modelItem.Commit();
655
                                    ReleaseCOMObjects(modelItem);
656
                                    modelItem = null;
657
                                }
658
                            }
659
                        }
660
                    }
661
                    ReleaseCOMObjects(symbol);
662
                    symbol = null;
663
                }
664
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
665
            }
666
        }
667
        private void RunClearValueInconsistancy()
668
        {
669
            int count = 1;
670
            bool loop = true;
671
            while (loop)
672
            {
673
                loop = false;
674
                LMAFilter filter = new LMAFilter();
675
                LMACriterion criterion = new LMACriterion();
676
                filter.ItemType = "Relationship";
677
                criterion.SourceAttributeName = "SP_DRAWINGID";
678
                criterion.Operator = "=";
679
                criterion.set_ValueAttribute(drawingID);
680
                filter.get_Criteria().Add(criterion);
681

    
682
                LMRelationships relationships = new LMRelationships();
683
                relationships.Collect(dataSource, Filter: filter);
684

    
685
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
686
                if (count > 1)
687
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
688
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
689
                foreach (LMRelationship relationship in relationships)
690
                {
691
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
692
                    {
693
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
694
                        {
695
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
696
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
697
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
698
                            if (modelItem1 != null)
699
                            {
700
                                string attrName = array[0];
701
                                if (attrName.Contains("PipingPoint"))
702
                                {
703
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
704
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
705
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
706
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
707
                                    {
708
                                        loop = true;
709
                                        attribute1.set_Value(DBNull.Value);
710
                                    }
711
                                    attribute1 = null;
712
                                }
713
                                else
714
                                {
715
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
716
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
717
                                    {
718
                                        loop = true;
719
                                        attribute1.set_Value(DBNull.Value);
720
                                    }
721
                                    attribute1 = null;
722
                                }
723
                                modelItem1.Commit();
724
                            }
725
                            if (modelItem2 != null)
726
                            {
727
                                string attrName = array[1];
728
                                if (attrName.Contains("PipingPoint"))
729
                                {
730
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
731
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
732
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
733
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
734
                                    {
735
                                        attribute2.set_Value(DBNull.Value);
736
                                        loop = true;
737
                                    }
738
                                    attribute2 = null;
739
                                }
740
                                else
741
                                {
742
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
743
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
744
                                    {
745
                                        attribute2.set_Value(DBNull.Value);
746
                                        loop = true;
747
                                    }
748
                                    attribute2 = null;
749
                                }
750
                                modelItem2.Commit();
751
                            }
752
                            ReleaseCOMObjects(modelItem1);
753
                            modelItem1 = null;
754
                            ReleaseCOMObjects(modelItem2);
755
                            modelItem2 = null;
756
                            inconsistency.Commit();
757
                        }
758
                        ReleaseCOMObjects(inconsistency);
759
                    }
760
                    relationship.Commit();
761
                    ReleaseCOMObjects(relationship);
762
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
763
                }
764
                ReleaseCOMObjects(filter);
765
                filter = null;
766
                ReleaseCOMObjects(criterion);
767
                criterion = null;
768
                ReleaseCOMObjects(relationships);
769
                relationships = null;
770
                count++;
771
            }
772
        }
773
        private void RunEndBreakModeling()
774
        {
775
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
776
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
777
            foreach (var item in document.EndBreaks)
778
                try
779
                {
780
                    EndBreakModeling(item);
781
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
782
                }
783
                catch (Exception ex)
784
                {
785
                    Log.Write("Error in EndBreakModeling");
786
                    Log.Write("UID : " + item.UID);
787
                    Log.Write(ex.Message);
788
                    Log.Write(ex.StackTrace);
789
                }
790
        }
791
        private void RunSpecBreakModeling()
792
        {
793
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
794
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
795
            foreach (var item in document.SpecBreaks)
796
                try
797
                {
798
                    SpecBreakModeling(item);
799
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
800
                }
801
                catch (Exception ex)
802
                {
803
                    Log.Write("Error in SpecBreakModeling");
804
                    Log.Write("UID : " + item.UID);
805
                    Log.Write(ex.Message);
806
                    Log.Write(ex.StackTrace);
807
                }
808
        }
809
        private void RunJoinRunForSameConnector()
810
        {
811
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
812
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
813
            foreach (var line in document.LINES)
814
            {
815
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
816
                List<List<double[]>> result = new List<List<double[]>>();
817
                foreach (var item in vertices)
818
                {
819
                    ReleaseCOMObjects(item.Key);
820
                    result.Add(item.Value);
821
                }
822
                line.SPPID.Vertices = result;
823
                vertices = null;
824
            }
825

    
826
            foreach (var line in document.LINES)
827
            {
828
                foreach (var connector in line.CONNECTORS)
829
                {
830
                    if (connector.ConnectedObject != null &&
831
                        connector.ConnectedObject.GetType() == typeof(Line) &&
832
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
833
                    {
834
                        Line connLine = connector.ConnectedObject as Line;
835

    
836
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
837
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
838
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
839
                            !SPPIDUtil.IsSegment(document, line, connLine))
840
                        {
841
                            string survivorId = string.Empty;
842
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
843
                        }
844

    
845
                    }
846
                }
847
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
848
            }
849

    
850
            foreach (var line in document.LINES)
851
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
852
        }
853
        private void RunJoinRun()
854
        {
855
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
856
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
857
            List<string> endModelID = new List<string>();
858
            foreach (var line in document.LINES)
859
            {
860
                if (!endModelID.Contains(line.SPPID.ModelItemId))
861
                {
862
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
863
                    {
864
                        string survivorId = string.Empty;
865
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
866
                        if (string.IsNullOrEmpty(survivorId))
867
                        {
868
                            endModelID.Add(line.SPPID.ModelItemId);
869
                        }
870
                    }
871
                }
872
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
873
            }
874
        }
875
        private void RunLineNumberModeling()
876
        {
877
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
878
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
879
            foreach (var item in document.LINENUMBERS)
880
            {
881
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
882
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
883
                {
884
                    ReleaseCOMObjects(label);
885
                    item.SPPID.RepresentationId = null;
886
                    LineNumberModeling(item);
887
                }
888
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
889
            }
890
        }
891
        private void RunNoteModeling()
892
        {
893
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
894
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
895
            List<Note> correctList = new List<Note>();
896
            foreach (var item in document.NOTES)
897
                try
898
                {
899
                    NoteModeling(item, correctList);
900
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
901
                }
902
                catch (Exception ex)
903
                {
904
                    Log.Write("Error in NoteModeling");
905
                    Log.Write("UID : " + item.UID);
906
                    Log.Write(ex.Message);
907
                    Log.Write(ex.StackTrace);
908
                }
909

    
910
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
911
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
912
            SortNote(correctList);
913
            List<Note> endList = new List<Note>();
914
            if (correctList.Count > 0)
915
                endList.Add(correctList[0]);
916
            foreach (var item in correctList)
917
                try
918
                {
919
                    if (!endList.Contains(item))
920
                        NoteCorrectModeling(item, endList);
921
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
922
                }
923
                catch (Exception ex)
924
                {
925
                    Log.Write("Error in NoteModeling");
926
                    Log.Write("UID : " + item.UID);
927
                    Log.Write(ex.Message);
928
                    Log.Write(ex.StackTrace);
929
                }
930
        }
931
        private void RunTextModeling()
932
        {
933
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
934
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
935
            SortText(document.TEXTINFOS);
936
            foreach (var item in document.TEXTINFOS)
937
                try
938
                {
939
                    if (item.ASSOCIATION)
940
                        AssociationTextModeling(item);
941
                    else
942
                        NormalTextModeling(item);
943
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
944
                }
945
                catch (Exception ex)
946
                {
947
                    Log.Write("Error in TextModeling");
948
                    Log.Write("UID : " + item.UID);
949
                    Log.Write(ex.Message);
950
                    Log.Write(ex.StackTrace);
951
                }
952
        }
953
        private void RunInputLineNumberAttribute()
954
        {
955
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
956
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
957
            List<string> endLine = new List<string>();
958
            foreach (var item in document.LINENUMBERS)
959
                try
960
                {
961
                    InputLineNumberAttribute(item, endLine);
962
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
963
                }
964
                catch (Exception ex)
965
                {
966
                    Log.Write("Error in InputLineNumberAttribute");
967
                    Log.Write("UID : " + item.UID);
968
                    Log.Write(ex.Message);
969
                    Log.Write(ex.StackTrace);
970
                }
971
        }
972
        private void RunInputSymbolAttribute()
973
        {
974
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.Equipments.Count + document.LINES.Count);
975
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
976
            foreach (var item in document.SYMBOLS)
977
                try
978
                {
979
                    InputSymbolAttribute(item, item.ATTRIBUTES);
980
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
981
                }
982
                catch (Exception ex)
983
                {
984
                    Log.Write("Error in InputSymbolAttribute");
985
                    Log.Write("UID : " + item.UID);
986
                    Log.Write(ex.Message);
987
                    Log.Write(ex.StackTrace);
988
                }
989

    
990
            foreach (var item in document.Equipments)
991
                try
992
                {
993
                    InputSymbolAttribute(item, item.ATTRIBUTES);
994
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
995
                }
996
                catch (Exception ex)
997
                {
998
                    Log.Write("Error in InputSymbolAttribute");
999
                    Log.Write("UID : " + item.UID);
1000
                    Log.Write(ex.Message);
1001
                    Log.Write(ex.StackTrace);
1002
                }
1003
            foreach (var item in document.LINES)
1004
                try
1005
                {
1006
                    InputSymbolAttribute(item, item.ATTRIBUTES);
1007
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1008
                }
1009
                catch (Exception ex)
1010
                {
1011
                    Log.Write("Error in InputSymbolAttribute");
1012
                    Log.Write("UID : " + item.UID);
1013
                    Log.Write(ex.Message);
1014
                    Log.Write(ex.StackTrace);
1015
                }
1016
        }
1017
        private void RunInputSpecBreakAttribute()
1018
        {
1019
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
1020
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
1021
            foreach (var item in document.SpecBreaks)
1022
                try
1023
                {
1024
                    InputSpecBreakAttribute(item);
1025
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1026
                }
1027
                catch (Exception ex)
1028
                {
1029
                    Log.Write("Error in InputSpecBreakAttribute");
1030
                    Log.Write("UID : " + item.UID);
1031
                    Log.Write(ex.Message);
1032
                    Log.Write(ex.StackTrace);
1033
                }
1034
        }
1035
        private void RunInputEndBreakAttribute()
1036
        {
1037
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
1038
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
1039
            foreach (var item in document.EndBreaks)
1040
                try
1041
                {
1042
                    InputEndBreakAttribute(item);
1043
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1044
                }
1045
                catch (Exception ex)
1046
                {
1047
                    Log.Write("Error in RunInputEndBreakAttribute");
1048
                    Log.Write("UID : " + item.UID);
1049
                    Log.Write(ex.Message);
1050
                    Log.Write(ex.StackTrace);
1051
                }
1052
        }
1053
        private void RunLabelSymbolModeling()
1054
        {
1055
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
1056
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
1057
            foreach (var item in document.SYMBOLS)
1058
                try
1059
                {
1060
                    LabelSymbolModeling(item);
1061
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1062
                }
1063
                catch (Exception ex)
1064
                {
1065
                    Log.Write("Error in LabelSymbolModeling");
1066
                    Log.Write("UID : " + item.UID);
1067
                    Log.Write(ex.Message);
1068
                    Log.Write(ex.StackTrace);
1069
                }
1070

    
1071
        }
1072
        private void RunCorrectAssociationText()
1073
        {
1074
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
1075
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
1076
            List<Text> endTexts = new List<Text>();
1077
            foreach (var item in document.TEXTINFOS)
1078
            {
1079
                try
1080
                {
1081
                    if (item.ASSOCIATION && !endTexts.Contains(item))
1082
                        AssociationTextCorrectModeling(item, endTexts);
1083
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1084
                }
1085
                catch (Exception ex)
1086
                {
1087
                    Log.Write("Error in RunCorrectAssociationText");
1088
                    Log.Write("UID : " + item.UID);
1089
                    Log.Write(ex.Message);
1090
                    Log.Write(ex.StackTrace);
1091
                }
1092

    
1093
            }
1094

    
1095
            foreach (var item in document.LINENUMBERS)
1096
            {
1097
                try
1098
                {
1099
                    LineNumberCorrectModeling(item);
1100
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1101
                }
1102
                catch (Exception ex)
1103
                {
1104
                    Log.Write("Error in RunCorrectAssociationText");
1105
                    Log.Write("UID : " + item.UID);
1106
                    Log.Write(ex.Message);
1107
                    Log.Write(ex.StackTrace);
1108
                }
1109
            }
1110
        }
1111
        private void RunETC()
1112
        {
1113
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, FlowMarkRepIds.Count);
1114
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "ETC");
1115
            foreach (var item in FlowMarkRepIds)
1116
            {
1117
                LMLabelPersist label = dataSource.GetLabelPersist(item);
1118
                if (label != null)
1119
                {
1120
                    label.get_GraphicOID();
1121
                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[label.get_GraphicOID().ToString()] as DependencyObject;
1122
                    if (dependency != null)
1123
                        dependency.BringToFront();
1124
                }
1125
                ReleaseCOMObjects(label);
1126
                label = null;
1127
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1128
            }
1129
        }
1130
        private void RunBulkAttribute()
1131
        {
1132
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, 2);
1133
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Bulk Attribute");
1134

    
1135
            List<SPPIDModel.BulkAttribute> select = _ETCSetting.BulkAttributes.FindAll(x => x.RuleName.Equals(document.BulkAttributeName));
1136
            if (select.Count > 0)
1137
                SPPIDUtil.BulkAttribute(dataSource, select, BulkAttributeItemType.PipeRun);
1138
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1139
            if (select.Count > 0)
1140
                SPPIDUtil.BulkAttribute(dataSource, select, BulkAttributeItemType.Symbol);
1141
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1142
        }
1143
        private void RunGraphicModeling()
1144
        {
1145
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Graphics.Count);
1146
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Graphic Modeling");
1147
            foreach (var item in document.Graphics)
1148
            {
1149
                try
1150
                {
1151
                    GraphicModeling(item);
1152
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1153
                }
1154
                catch (Exception ex)
1155
                {
1156
                    Log.Write("Error in GrahicModeling");
1157
                    Log.Write("UID : " + item.UID);
1158
                    Log.Write(ex.Message);
1159
                    Log.Write(ex.StackTrace);
1160
                }
1161
            }
1162
        }
1163
        private void RunUpdatePipeRunProperties()
1164
        {
1165
            DataTable dt = Project_DB.SelectPipeRunPropSetting();
1166
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, dt == null ? 0 : dt.Rows.Count);
1167
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Update PipeRun Properties");
1168

    
1169
            if (dt == null) return;
1170
            foreach (DataRow dr in dt.Rows)
1171
            {
1172
                Model.SPPID_PipeRunPropSetting setting = new SPPID_PipeRunPropSetting(dr);
1173
                if (setting.Cond1_DataType.StartsWith("C") || setting.Cond1_Value.Contains(",") && setting.Cond2_DataType.StartsWith("C") || setting.Cond2_Value.Contains(","))
1174
                {
1175
                    string[] value1_Arr = setting.Cond1_Value.Split(',');
1176
                    string[] value2_Arr = setting.Cond2_Value.Split(',');
1177

    
1178
                    for (int i = 0; i < value1_Arr.Length; i++)
1179
                    {
1180
                        for (int j = 0; j < value2_Arr.Length; j++)
1181
                        {
1182
                            setting.Cond1_Value = value1_Arr[i].Trim();
1183
                            setting.Cond2_Value = value2_Arr[j].Trim();
1184
                            SPPIDUtil.UpdatePipeRunProperty(dataSource, setting);
1185
                        }
1186
                    }
1187
                }
1188
                else if (setting.Cond1_DataType.StartsWith("C") || setting.Cond1_Value.Contains(","))
1189
                {
1190
                    string[] value1_Arr = setting.Cond1_Value.Split(',');
1191

    
1192
                    for (int i = 0; i < value1_Arr.Length; i++)
1193
                    {
1194
                        setting.Cond1_Value = value1_Arr[i].Trim();
1195
                        SPPIDUtil.UpdatePipeRunProperty(dataSource, setting);
1196
                    }
1197
                }
1198
                else if (setting.Cond2_DataType.StartsWith("C") || setting.Cond2_Value.Contains(","))
1199
                {
1200
                    string[] value2_Arr = setting.Cond2_Value.Split(',');
1201

    
1202
                    for (int i = 0; i < value2_Arr.Length; i++)
1203
                    {
1204
                        setting.Cond2_Value = value2_Arr[i].Trim();
1205
                        SPPIDUtil.UpdatePipeRunProperty(dataSource, setting);
1206
                    }
1207
                }
1208
                else
1209
                {
1210
                    SPPIDUtil.UpdatePipeRunProperty(dataSource, setting);
1211
                }
1212
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1213
            }
1214
        }
1215
        /// <summary>
1216
        /// 도면 생성 메서드
1217
        /// </summary>
1218
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1219
        {
1220
            Log.Write("------------------ Start create document ------------------");
1221
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1222
            Log.Write("Drawing name : " + drawingName);
1223
            Log.Write("Drawing number : " + drawingNumber);
1224
            Thread.Sleep(1000);
1225
            try
1226
            {
1227
                newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1228
            }
1229
            catch (Exception ex)
1230
            {
1231
                if (ex.Message == "Invalid procedure call or argument")
1232
                {
1233
                    Exception newEx = new Exception(string.Format("Invalid Unit [0]", document.Unit), ex.InnerException);
1234
                    throw newEx;
1235
                }
1236
                else
1237
                {
1238
                    throw ex;
1239
                }
1240
            }
1241

    
1242
            if (newDrawing != null)
1243
            {
1244
                document.SPPID_DrawingNumber = drawingNumber;
1245
                document.SPPID_DrawingName = drawingName;
1246
                Thread.Sleep(1000);
1247
                radApp.ActiveWindow.Fit();
1248
                Thread.Sleep(1000);
1249
                radApp.ActiveWindow.Zoom = 2000;
1250
                Thread.Sleep(2000);
1251

    
1252
                //current LMDrawing 가져오기
1253
                LMAFilter filter = new LMAFilter();
1254
                LMACriterion criterion = new LMACriterion();
1255
                filter.ItemType = "Drawing";
1256
                criterion.SourceAttributeName = "Name";
1257
                criterion.Operator = "=";
1258
                criterion.set_ValueAttribute(drawingName);
1259
                filter.get_Criteria().Add(criterion);
1260

    
1261
                LMDrawings drawings = new LMDrawings();
1262
                drawings.Collect(dataSource, Filter: filter);
1263

    
1264
                // Input Drawing Attribute
1265
                LMDrawing drawing = ((dynamic)drawings).Nth(1);
1266
                if (drawing != null)
1267
                {
1268
                    using (DataTable drawingAttributeDT = Project_DB.SelectDrawingProjectAttribute())
1269
                    {
1270
                        foreach (DataRow row in drawingAttributeDT.Rows)
1271
                        {
1272
                            string mappingName = DBNull.Value.Equals(row["SPPID_ATTRIBUTE"]) ? string.Empty : row["SPPID_ATTRIBUTE"].ToString();
1273
                            if (!string.IsNullOrEmpty(mappingName))
1274
                            {
1275
                                string uid = row["UID"].ToString();
1276
                                string name = row["NAME"].ToString();
1277
                                Text text = document.TEXTINFOS.Find(x => x.AREA == uid);
1278
                                if (text != null)
1279
                                {
1280
                                    string value = text.VALUE;
1281
                                    LMAAttribute attribute = drawing.Attributes[mappingName];
1282
                                    if (attribute != null)
1283
                                        attribute.set_Value(value);
1284
                                    ReleaseCOMObjects(attribute);
1285
                                    document.TEXTINFOS.Remove(text);
1286
                                }
1287
                            }
1288
                        }
1289

    
1290
                        drawingAttributeDT.Dispose();
1291
                    }
1292

    
1293
                    ReleaseCOMObjects(drawing);
1294
                }
1295

    
1296
                drawingID = ((dynamic)drawings).Nth(1).Id;
1297
                ReleaseCOMObjects(filter);
1298
                ReleaseCOMObjects(criterion);
1299
                ReleaseCOMObjects(drawings);
1300
                filter = null;
1301
                criterion = null;
1302
                drawings = null;
1303
            }
1304
            else
1305
                Log.Write("Fail Create Drawing");
1306

    
1307
            if (newDrawing != null)
1308
            {
1309
                SetBorderFile();
1310
                return true;
1311
            }
1312
            else
1313
                return false;
1314
        }
1315

    
1316
        private void SetBorderFile()
1317
        {
1318
            ETCSetting setting = ETCSetting.GetInstance();
1319

    
1320
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1321
            {
1322
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1323
                {
1324
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1325
                    {
1326
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1327
                        smartFrame.Update();
1328
                    }
1329

    
1330
                }
1331
            }
1332
        }
1333

    
1334
        /// <summary>
1335
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1336
        /// </summary>
1337
        /// <param name="drawingName"></param>
1338
        /// <param name="drawingNumber"></param>
1339
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1340
        {
1341
            LMDrawings drawings = new LMDrawings();
1342
            drawings.Collect(dataSource);
1343

    
1344
            List<string> drawingNameList = new List<string>();
1345
            List<string> drawingNumberList = new List<string>();
1346

    
1347
            foreach (LMDrawing item in drawings)
1348
            {
1349
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1350
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1351
            }
1352

    
1353
            int nameLength = drawingName.Length;
1354
            while (drawingNameList.Contains(drawingName))
1355
            {
1356
                if (nameLength == drawingName.Length)
1357
                    drawingName += "-1";
1358
                else
1359
                {
1360
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1361
                    drawingName = drawingName.Substring(0, nameLength + 1);
1362
                    drawingName += ++index;
1363
                }
1364
            }
1365

    
1366
            int numberLength = drawingNumber.Length;
1367
            while (drawingNameList.Contains(drawingNumber))
1368
            {
1369
                if (numberLength == drawingNumber.Length)
1370
                    drawingNumber += "-1";
1371
                else
1372
                {
1373
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1374
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1375
                    drawingNumber += ++index;
1376
                }
1377
            }
1378
            ReleaseCOMObjects(drawings);
1379
            drawings = null;
1380
        }
1381

    
1382
        /// <summary>
1383
        /// 도면 크기 구하는 메서드
1384
        /// </summary>
1385
        /// <returns></returns>
1386
        private bool DocumentCoordinateCorrection()
1387
        {
1388
            //if (radApp.ActiveDocument.ActiveSheet.SmartFrames2d.Count > 0)
1389
            //{
1390
            //    double x = 0;
1391
            //    double y = 0;
1392
            //    foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1393
            //    {
1394
            //        x = Math.Max(smartFrame.CropRight, x);
1395
            //        y = Math.Max(smartFrame.CropTop, y);
1396
            //    }
1397
            //    document.SetSPPIDLocation(x, y);
1398
            //    document.CoordinateCorrection();
1399
            //    return true;
1400
            //}
1401
            //else
1402
            //{
1403
            //    Log.Write("Need Border!");
1404
            //    return false;
1405
            //}
1406

    
1407
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1408
            {
1409
                Log.Write("Setting Drawing X, Drawing Y");
1410
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1411
                Log.Write("Start coordinate correction");
1412
                document.CoordinateCorrection();
1413
                return true;
1414
            }
1415
            else
1416
            {
1417
                Log.Write("Need Drawing X, Y");
1418
                return false;
1419
            }
1420
        }
1421

    
1422
        /// <summary>
1423
        /// 심볼을 실제로 Modeling 메서드
1424
        /// </summary>
1425
        /// <param name="symbol">생성할 심볼</param>
1426
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1427
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1428
        {
1429
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1430
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1431
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1432
                return;
1433
            // 이미 모델링 됐을 경우
1434
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1435
                return;
1436

    
1437
            LMSymbol _LMSymbol = null;
1438

    
1439
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1440
            double x = symbol.SPPID.ORIGINAL_X;
1441
            double y = symbol.SPPID.ORIGINAL_Y;
1442
            int mirror = 0;
1443
            double angle = symbol.ANGLE;
1444

    
1445
            // OPC 일경우 180도 일때 Mirror
1446
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1447
                mirror = 1;
1448

    
1449
            // Mirror 계산
1450
            if (symbol.FLIP == 1)
1451
            {
1452
                mirror = 1;
1453
                if (angle == Math.PI || angle == 0)
1454
                    angle += Math.PI;
1455
            }
1456

    
1457
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1458
            {
1459
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1460
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1461
                if (connector != null)
1462
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1463

    
1464
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1465
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1466
                if (temp != null)
1467
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1468
                ReleaseCOMObjects(temp);
1469
                temp = null;
1470

    
1471
                if (_LMSymbol != null && _TargetItem != null)
1472
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1473

    
1474
                ReleaseCOMObjects(_TargetItem);
1475
            }
1476
            else
1477
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1478

    
1479
            if (_LMSymbol != null)
1480
            {
1481
                _LMSymbol.Commit();
1482

    
1483
                // ConnCheck
1484
                List<string> ids = new List<string>();
1485
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1486
                {
1487
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1488
                        ids.Add(item.Id);
1489
                    ReleaseCOMObjects(item);
1490
                }
1491
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1492
                {
1493
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1494
                        ids.Add(item.Id);
1495
                    ReleaseCOMObjects(item);
1496
                }
1497

    
1498
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1499
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1500
                {
1501
                    double currentX = _LMSymbol.get_XCoordinate();
1502
                    double currentY = _LMSymbol.get_YCoordinate();
1503
                }
1504

    
1505
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1506
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1507
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1508

    
1509
                foreach (var item in symbol.ChildSymbols)
1510
                    CreateChildSymbol(item, _LMSymbol, symbol);
1511

    
1512
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1513
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1514

    
1515
                double[] range = null;
1516
                GetSPPIDSymbolRange(symbol, ref range);
1517
                symbol.SPPID.SPPID_Min_X = range[0];
1518
                symbol.SPPID.SPPID_Min_Y = range[1];
1519
                symbol.SPPID.SPPID_Max_X = range[2];
1520
                symbol.SPPID.SPPID_Max_Y = range[3];
1521

    
1522
                double xGap = symbol.SPPID.SPPID_X - symbol.SPPID.ORIGINAL_X;
1523
                double yGap = symbol.SPPID.SPPID_Y - symbol.SPPID.ORIGINAL_Y;
1524

    
1525
                List<Symbol> xGroupSymbols = symbol.SPPID.CorrectionX_GroupSymbols;
1526
                List<Symbol> yGroupSymbols = symbol.SPPID.CorrectionY_GroupSymbols;
1527
                xGroupSymbols.Sort(SPPIDUtil.SortSymbolPriority);
1528
                yGroupSymbols.Sort(SPPIDUtil.SortSymbolPriority);
1529
                int xDrawnCount = xGroupSymbols.Count(c => c.SPPID.RepresentationId != null);
1530
                int yDrawnCount = yGroupSymbols.Count(c => c.SPPID.RepresentationId != null);
1531

    
1532
                if (xDrawnCount == 1 || xDrawnCount == 2)
1533
                {
1534
                    for (int i = 0; i < xGroupSymbols.Count; i++)
1535
                    {
1536
                        var item = xGroupSymbols[i];
1537
                        if (!string.IsNullOrWhiteSpace(item.SPPID.RepresentationId)) continue;
1538

    
1539
                        if (xDrawnCount == 1)
1540
                        {
1541
                            item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1542
                            item.SPPID.ORIGINAL_Y = item.SPPID.ORIGINAL_Y + yGap;
1543
                        }
1544
                        else if (xDrawnCount == 2)
1545
                        {
1546
                            if (item.SPPID.IsEqualSpacingY)
1547
                            {
1548
                                double ppValue = xGroupSymbols[i - 2].SPPID.SPPID_Y != 0 ? xGroupSymbols[i - 2].SPPID.SPPID_Y : xGroupSymbols[i - 2].SPPID.ORIGINAL_Y;
1549
                                double pValue = xGroupSymbols[i - 1].SPPID.SPPID_Y != 0 ? xGroupSymbols[i - 1].SPPID.SPPID_Y : xGroupSymbols[i - 1].SPPID.ORIGINAL_Y;
1550
                                double gap = pValue - ppValue;
1551
                                double value = pValue + gap;
1552
                                item.SPPID.ORIGINAL_Y = value;
1553
                            }
1554
                        }
1555
                    }
1556
                }
1557

    
1558
                if (yDrawnCount == 1 || yDrawnCount == 2)
1559
                {
1560
                    for (int i = 0; i < yGroupSymbols.Count; i++)
1561
                    {
1562
                        var item = yGroupSymbols[i];
1563
                        if (!string.IsNullOrWhiteSpace(item.SPPID.RepresentationId)) continue;
1564

    
1565
                        if (yDrawnCount == 1)
1566
                        {
1567
                            item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1568
                            item.SPPID.ORIGINAL_X = item.SPPID.ORIGINAL_X + xGap;
1569
                        }
1570
                        else if (yDrawnCount == 2)
1571
                        {
1572
                            if (item.SPPID.IsEqualSpacingX)
1573
                            {
1574
                                double ppValue = yGroupSymbols[i - 2].SPPID.SPPID_X != 0 ? yGroupSymbols[i - 2].SPPID.SPPID_X : yGroupSymbols[i - 2].SPPID.ORIGINAL_X;
1575
                                double pValue = yGroupSymbols[i - 1].SPPID.SPPID_X != 0 ? yGroupSymbols[i - 1].SPPID.SPPID_X : yGroupSymbols[i - 1].SPPID.ORIGINAL_X;
1576
                                double gap = pValue - ppValue;
1577
                                double value = pValue + gap;
1578
                                item.SPPID.ORIGINAL_X = value;
1579
                            }
1580
                        }
1581
                    }
1582
                }
1583

    
1584
                ReleaseCOMObjects(_LMSymbol);
1585
            }
1586
        }
1587
        /// <summary>
1588
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1589
        /// Signal Point는 고려하지 않음
1590
        /// </summary>
1591
        /// <param name="symbol"></param>
1592
        /// <param name="_TargetItem"></param>
1593
        /// <param name="targetX"></param>
1594
        /// <param name="targetY"></param>
1595
        /// <returns></returns>
1596
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1597
        {
1598
            LMConnector tempConnector = null;
1599

    
1600
            List<Symbol> group = new List<Symbol>();
1601
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1602
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1603
            {
1604
                List<Connector> connectors = new List<Connector>();
1605
                foreach (var item in group)
1606
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1607
                /// Primary or Secondary Type Line만 고려
1608
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1609
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1610
                if (_connector != null)
1611
                {
1612
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1613
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1614
                    /// PipingPoint가 2개 이상만
1615
                    if (pointInfos.Count >= 2)
1616
                    {
1617
                        double lineX = 0;
1618
                        double lineY = 0;
1619
                        double length = 0;
1620
                        foreach (var item in pointInfos)
1621
                        {
1622
                            double tempX = item[1];
1623
                            double tempY = item[2];
1624

    
1625
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1626
                            if (calcDistance > length)
1627
                            {
1628
                                lineX = tempX;
1629
                                lineY = tempY;
1630
                            }
1631
                        }
1632

    
1633
                        _LMAItem lMAItem = _placement.PIDCreateItem(sppidLine);
1634
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1635
                        placeRunInputs.AddPoint(-1, -1);
1636
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1637
                        tempConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
1638
                        if (tempConnector != null)
1639
                            tempConnector.Commit();
1640
                        ReleaseCOMObjects(lMAItem);
1641
                        lMAItem = null;
1642
                        ReleaseCOMObjects(placeRunInputs);
1643
                        placeRunInputs = null;
1644
                    }
1645
                }
1646
            }
1647

    
1648
            return tempConnector;
1649
        }
1650
        /// <summary>
1651
        /// Symbol의 PipingPoints를 구함
1652
        /// SignalPoint는 고려하지 않음
1653
        /// </summary>
1654
        /// <param name="symbol"></param>
1655
        /// <returns></returns>
1656
        private List<double[]> getPipingPoints(LMSymbol symbol)
1657
        {
1658
            LMModelItem modelItem = symbol.ModelItemObject;
1659
            LMPipingPoints pipingPoints = null;
1660
            if (modelItem.get_ItemTypeName() == "PipingComp")
1661
            {
1662
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1663
                pipingPoints = pipingComp.PipingPoints;
1664
                ReleaseCOMObjects(pipingComp);
1665
                pipingComp = null;
1666
            }
1667
            else if (modelItem.get_ItemTypeName() == "Instrument")
1668
            {
1669
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1670
                pipingPoints = instrument.PipingPoints;
1671
                ReleaseCOMObjects(instrument);
1672
                instrument = null;
1673
            }
1674
            else
1675
                Log.Write("다른 Type");
1676

    
1677
            List<double[]> info = new List<double[]>();
1678
            if (pipingPoints != null)
1679
            {
1680
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1681
                {
1682
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1683
                    {
1684
                        if (attribute.Name == "PipingPointNumber")
1685
                        {
1686
                            int index = Convert.ToInt32(attribute.get_Value());
1687
                            if (info.Find(loopX => loopX[0] == index) == null)
1688
                            {
1689
                                double x = 0;
1690
                                double y = 0;
1691
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1692
                                    info.Add(new double[] { index, x, y });
1693
                            }
1694
                        }
1695
                    }
1696
                }
1697
            }
1698
            ReleaseCOMObjects(modelItem);
1699
            modelItem = null;
1700
            ReleaseCOMObjects(pipingPoints);
1701
            pipingPoints = null;
1702

    
1703
            return info;
1704
        }
1705

    
1706
        private void RemoveSymbol(Symbol symbol)
1707
        {
1708
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1709
            {
1710
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1711
                if (_LMSymbol != null)
1712
                {
1713
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1714
                    ReleaseCOMObjects(_LMSymbol);
1715
                }
1716
            }
1717

    
1718
            symbol.SPPID.RepresentationId = string.Empty;
1719
            symbol.SPPID.ModelItemID = string.Empty;
1720
            symbol.SPPID.SPPID_X = double.NaN;
1721
            symbol.SPPID.SPPID_Y = double.NaN;
1722
            symbol.SPPID.SPPID_Min_X = double.NaN;
1723
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1724
            symbol.SPPID.SPPID_Max_X = double.NaN;
1725
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1726
        }
1727

    
1728
        private void RemoveSymbol(List<Symbol> symbols)
1729
        {
1730
            foreach (var symbol in symbols)
1731
            {
1732
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1733
                {
1734
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1735
                    if (_LMSymbol != null)
1736
                    {
1737
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1738
                        ReleaseCOMObjects(_LMSymbol);
1739
                    }
1740
                }
1741

    
1742
                symbol.SPPID.RepresentationId = string.Empty;
1743
                symbol.SPPID.ModelItemID = string.Empty;
1744
                symbol.SPPID.SPPID_X = double.NaN;
1745
                symbol.SPPID.SPPID_Y = double.NaN;
1746
                symbol.SPPID.SPPID_Min_X = double.NaN;
1747
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1748
                symbol.SPPID.SPPID_Max_X = double.NaN;
1749
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1750
            }
1751
        }
1752

    
1753
        /// <summary>
1754
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1755
        /// </summary>
1756
        /// <param name="targetConnector"></param>
1757
        /// <param name="targetSymbol"></param>
1758
        /// <param name="x"></param>
1759
        /// <param name="y"></param>
1760
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1761
        {
1762
            if (targetSymbol == null || targetSymbol.SPPID.RepresentationId == null) return;
1763

    
1764
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1765

    
1766
            double[] range = null;
1767
            List<double[]> points = new List<double[]>();
1768
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1769
            double x1 = range[0];
1770
            double y1 = range[1];
1771
            double x2 = range[2];
1772
            double y2 = range[3];
1773

    
1774
            // Origin 기준 Connector의 위치차이
1775
            double sceneX = 0;
1776
            double sceneY = 0;
1777
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1778
            double originX = 0;
1779
            double originY = 0;
1780
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1781
            double gapX = originX - sceneX;
1782
            double gapY = originY - sceneY;
1783

    
1784
            // SPPID Symbol과 ID2 심볼의 크기 차이
1785
            double sizeWidth = 0;
1786
            double sizeHeight = 0;
1787
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1788
            if (sizeWidth == 0 || sizeHeight == 0)
1789
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1790

    
1791
            double percentX = (x2 - x1) / sizeWidth;
1792
            double percentY = (y2 - y1) / sizeHeight;
1793

    
1794
            double SPPIDgapX = gapX * percentX;
1795
            double SPPIDgapY = gapY * percentY;
1796

    
1797
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1798
            double distance = double.MaxValue;
1799
            double[] resultPoint;
1800
            foreach (var point in points)
1801
            {
1802
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1803
                if (distance > result)
1804
                {
1805
                    distance = result;
1806
                    resultPoint = point;
1807
                    x = point[0];
1808
                    y = point[1];
1809
                }
1810
            }
1811

    
1812
            ReleaseCOMObjects(_TargetItem);
1813
        }
1814

    
1815
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1816
        {
1817
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1818
            if (index == 0)
1819
            {
1820
                x = targetLine.SPPID.START_X;
1821
                y = targetLine.SPPID.START_Y;
1822
            }
1823
            else
1824
            {
1825
                x = targetLine.SPPID.END_X;
1826
                y = targetLine.SPPID.END_Y;
1827
            }
1828
        }
1829

    
1830
        /// <summary>
1831
        /// SPPID Symbol의 Range를 구한다.
1832
        /// </summary>
1833
        /// <param name="symbol"></param>
1834
        /// <param name="range"></param>
1835
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1836
        {
1837
            if (symbol == null || symbol.SPPID.RepresentationId == null) return;
1838
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1839
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1840
            double x1 = 0;
1841
            double y1 = 0;
1842
            double x2 = 0;
1843
            double y2 = 0;
1844
            symbol2d.Range(out x1, out y1, out x2, out y2);
1845
            range = new double[] { x1, y1, x2, y2 };
1846

    
1847
            for (int i = 1; i < 30; i++)
1848
            {
1849
                double connX = 0;
1850
                double connY = 0;
1851
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1852
                    points.Add(new double[] { connX, connY });
1853
            }
1854

    
1855
            foreach (var childSymbol in symbol.ChildSymbols)
1856
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1857

    
1858
            ReleaseCOMObjects(_TargetItem);
1859
        }
1860

    
1861
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1862
        {
1863
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1864
            if (_TargetItem != null)
1865
            {
1866
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1867
                double x1 = 0;
1868
                double y1 = 0;
1869
                double x2 = 0;
1870
                double y2 = 0;
1871
                if (!bForGraphic)
1872
                {
1873
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1874
                    range = new double[] { x1, y1, x2, y2 };
1875
                }
1876
                else
1877
                {
1878
                    x1 = double.MaxValue;
1879
                    y1 = double.MaxValue;
1880
                    x2 = double.MinValue;
1881
                    y2 = double.MinValue;
1882
                    range = new double[] { x1, y1, x2, y2 };
1883

    
1884
                    foreach (var item in symbol2d.DrawingObjects)
1885
                    {
1886
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1887
                        {
1888
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1889
                            if (rangeObject.Layer == "Default")
1890
                            {
1891
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1892
                                range = new double[] {
1893
                                Math.Min(x1, range[0]),
1894
                                Math.Min(y1, range[1]),
1895
                                Math.Max(x2, range[2]),
1896
                                Math.Max(y2, range[3])
1897
                            };
1898
                            }
1899
                        }
1900
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1901
                        {
1902
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1903
                            if (rangeObject.Layer == "Default")
1904
                            {
1905
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1906
                                range = new double[] {
1907
                                Math.Min(x1, range[0]),
1908
                                Math.Min(y1, range[1]),
1909
                                Math.Max(x2, range[2]),
1910
                                Math.Max(y2, range[3])
1911
                            };
1912
                            }
1913
                        }
1914
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1915
                        {
1916
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1917
                            if (rangeObject.Layer == "Default")
1918
                            {
1919
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1920
                                range = new double[] {
1921
                                Math.Min(x1, range[0]),
1922
                                Math.Min(y1, range[1]),
1923
                                Math.Max(x2, range[2]),
1924
                                Math.Max(y2, range[3])
1925
                            };
1926
                            }
1927
                        }
1928
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1929
                        {
1930
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1931
                            if (rangeObject.Layer == "Default")
1932
                            {
1933
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1934
                                range = new double[] {
1935
                                Math.Min(x1, range[0]),
1936
                                Math.Min(y1, range[1]),
1937
                                Math.Max(x2, range[2]),
1938
                                Math.Max(y2, range[3])
1939
                            };
1940
                            }
1941
                        }
1942
                    }
1943
                }
1944

    
1945
                if (!bOnlySymbol)
1946
                {
1947
                    foreach (var childSymbol in symbol.ChildSymbols)
1948
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1949
                }
1950
                ReleaseCOMObjects(_TargetItem);
1951
            }
1952
        }
1953

    
1954
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1955
        {
1956
            if (labelPersist != null)
1957
            {
1958
                double x1 = double.MaxValue;
1959
                double y1 = double.MaxValue;
1960
                double x2 = double.MinValue;
1961
                double y2 = double.MinValue;
1962
                range = new double[] { x1, y1, x2, y2 };
1963

    
1964
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1965
                foreach (var item in dependency.DrawingObjects)
1966
                {
1967
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1968
                    if (textBox != null)
1969
                    {
1970
                        if (dependency != null)
1971
                        {
1972
                            double tempX1;
1973
                            double tempY1;
1974
                            double tempX2;
1975
                            double tempY2;
1976
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1977
                            x1 = Math.Min(x1, tempX1);
1978
                            y1 = Math.Min(y1, tempY1);
1979
                            x2 = Math.Max(x2, tempX2);
1980
                            y2 = Math.Max(y2, tempY2);
1981

    
1982
                            range = new double[] { x1, y1, x2, y2 };
1983
                        }
1984
                    }
1985
                }
1986

    
1987
            }
1988
        }
1989

    
1990
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1991
        {
1992
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1993
            foreach (var symbol in symbols)
1994
            {
1995
                double[] symbolRange = null;
1996
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
1997

    
1998
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
1999
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
2000
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
2001
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
2002

    
2003
                foreach (var childSymbol in symbol.ChildSymbols)
2004
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
2005
            }
2006

    
2007
            range = tempRange;
2008
        }
2009

    
2010
        /// <summary>
2011
        /// Child Modeling 된 Symbol의 Range를 구한다.
2012
        /// </summary>
2013
        /// <param name="childSymbol"></param>
2014
        /// <param name="range"></param>
2015
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
2016
        {
2017
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
2018
            if (_ChildSymbol != null)
2019
            {
2020
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
2021
                double x1 = 0;
2022
                double y1 = 0;
2023
                double x2 = 0;
2024
                double y2 = 0;
2025
                symbol2d.Range(out x1, out y1, out x2, out y2);
2026
                range[0] = Math.Min(range[0], x1);
2027
                range[1] = Math.Min(range[1], y1);
2028
                range[2] = Math.Max(range[2], x2);
2029
                range[3] = Math.Max(range[3], y2);
2030

    
2031
                for (int i = 1; i < int.MaxValue; i++)
2032
                {
2033
                    double connX = 0;
2034
                    double connY = 0;
2035
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
2036
                        points.Add(new double[] { connX, connY });
2037
                    else
2038
                        break;
2039
                }
2040

    
2041
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
2042
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
2043

    
2044
                ReleaseCOMObjects(_ChildSymbol);
2045
            }
2046
        }
2047

    
2048
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
2049
        {
2050
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
2051
            if (_ChildSymbol != null)
2052
            {
2053
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
2054
                double x1 = 0;
2055
                double y1 = 0;
2056
                double x2 = 0;
2057
                double y2 = 0;
2058
                symbol2d.Range(out x1, out y1, out x2, out y2);
2059
                range[0] = Math.Min(range[0], x1);
2060
                range[1] = Math.Min(range[1], y1);
2061
                range[2] = Math.Max(range[2], x2);
2062
                range[3] = Math.Max(range[3], y2);
2063

    
2064
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
2065
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
2066
                ReleaseCOMObjects(_ChildSymbol);
2067
            }
2068
        }
2069

    
2070
        /// <summary>
2071
        /// Label Symbol Modeling
2072
        /// </summary>
2073
        /// <param name="symbol"></param>
2074
        private void LabelSymbolModeling(Symbol symbol)
2075
        {
2076
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
2077
            {
2078
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
2079
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
2080
                    return;
2081
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
2082

    
2083
                string symbolUID = itemAttribute.VALUE;
2084
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
2085
                if (targetItem != null &&
2086
                    (targetItem.GetType() == typeof(Symbol) ||
2087
                    targetItem.GetType() == typeof(Equipment)))
2088
                {
2089
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
2090
                    string sRep = null;
2091
                    if (targetItem.GetType() == typeof(Symbol))
2092
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
2093
                    else if (targetItem.GetType() == typeof(Equipment))
2094
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
2095
                    if (!string.IsNullOrEmpty(sRep))
2096
                    {
2097
                        // LEADER Line 검사
2098
                        bool leaderLine = false;
2099
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
2100
                        if (symbolMapping != null)
2101
                            leaderLine = symbolMapping.LEADERLINE;
2102

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

    
2107
                        //Leader 선 센터로
2108
                        if (_LMLabelPresist != null)
2109
                        {
2110
                            // Target Item에 Label의 Attribute Input
2111
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
2112

    
2113
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
2114
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
2115
                            if (dependency != null)
2116
                            {
2117
                                bool result = false;
2118
                                foreach (var attributes in dependency.AttributeSets)
2119
                                {
2120
                                    foreach (var attribute in attributes)
2121
                                    {
2122
                                        string name = attribute.Name;
2123
                                        string value = attribute.GetValue().ToString();
2124
                                        if (name == "DrawingItemType" && value == "LabelPersist")
2125
                                        {
2126
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
2127
                                            {
2128
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
2129
                                                {
2130
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
2131
                                                    double prevX = _TargetItem.get_XCoordinate();
2132
                                                    double prevY = _TargetItem.get_YCoordinate();
2133
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
2134
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
2135
                                                    result = true;
2136
                                                    break;
2137
                                                }
2138
                                            }
2139
                                        }
2140

    
2141
                                        if (result)
2142
                                            break;
2143
                                    }
2144

    
2145
                                    if (result)
2146
                                        break;
2147
                                }
2148
                            }
2149

    
2150
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
2151
                            _LMLabelPresist.Commit();
2152
                            ReleaseCOMObjects(_LMLabelPresist);
2153
                        }
2154

    
2155
                        ReleaseCOMObjects(_TargetItem);
2156
                    }
2157
                }
2158
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
2159
                {
2160
                    Line targetLine = targetItem as Line;
2161
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2162
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
2163
                    if (connectedLMConnector != null)
2164
                    {
2165
                        // Target Item에 Label의 Attribute Input
2166
                        InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
2167

    
2168
                        // LEADER Line 검사
2169
                        bool leaderLine = false;
2170
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
2171
                        if (symbolMapping != null)
2172
                            leaderLine = symbolMapping.LEADERLINE;
2173

    
2174
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: symbol.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
2175
                        if (_LMLabelPresist != null)
2176
                        {
2177
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
2178
                            _LMLabelPresist.Commit();
2179
                            ReleaseCOMObjects(_LMLabelPresist);
2180
                        }
2181
                        ReleaseCOMObjects(connectedLMConnector);
2182
                    }
2183

    
2184
                    foreach (var item in connectorVertices)
2185
                        if (item.Key != null)
2186
                            ReleaseCOMObjects(item.Key);
2187
                }
2188
            }
2189
        }
2190

    
2191
        /// <summary>
2192
        /// Equipment를 실제로 Modeling 메서드
2193
        /// </summary>
2194
        /// <param name="equipment"></param>
2195
        private void EquipmentModeling(Equipment equipment)
2196
        {
2197
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
2198
                return;
2199

    
2200
            LMSymbol _LMSymbol = null;
2201
            LMSymbol targetItem = null;
2202
            string mappingPath = equipment.SPPID.MAPPINGNAME;
2203
            double x = equipment.SPPID.ORIGINAL_X;
2204
            double y = equipment.SPPID.ORIGINAL_Y;
2205
            int mirror = 0;
2206
            double angle = equipment.ANGLE;
2207

    
2208
            // Mirror 계산
2209
            if (equipment.FLIP == 1)
2210
            {
2211
                mirror = 1;
2212
                if (angle == Math.PI || angle == 0)
2213
                    angle += Math.PI;
2214
            }
2215

    
2216
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
2217

    
2218
            Connector connector = equipment.CONNECTORS.Find(conn =>
2219
            !string.IsNullOrEmpty(conn.CONNECTEDITEM) &&
2220
            conn.CONNECTEDITEM != "None" &&
2221
            conn.ConnectedObject.GetType() == typeof(Equipment));
2222

    
2223
            if (connector != null)
2224
            {
2225
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
2226
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
2227
                if (connEquipment != null)
2228
                {
2229
                    //if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2230
                    //    EquipmentModeling(connEquipment);
2231

    
2232
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2233
                    {
2234
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
2235
                        if (targetItem != null)
2236
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2237
                        else
2238
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2239
                    }
2240
                    else
2241
                    {
2242
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2243
                    }
2244
                }
2245
                else if (connVendorPackage != null)
2246
                {
2247
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
2248
                    {
2249
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
2250
                        if (targetItem != null)
2251
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2252
                        else
2253
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2254
                    }
2255
                }
2256
                else
2257
                {
2258
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2259
                }
2260
            }
2261
            else
2262
            {
2263
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2264
            }
2265

    
2266
            if (_LMSymbol != null)
2267
            {
2268
                _LMSymbol.Commit();
2269
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2270
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
2271
                ReleaseCOMObjects(_LMSymbol);
2272
            }
2273

    
2274
            if (targetItem != null)
2275
            {
2276
                ReleaseCOMObjects(targetItem);
2277
            }
2278

    
2279
            ReleaseCOMObjects(_LMSymbol);
2280
        }
2281

    
2282
        private void VendorPackageModeling(VendorPackage vendorPackage)
2283
        {
2284
            ETCSetting setting = ETCSetting.GetInstance();
2285
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2286
            {
2287
                string symbolPath = setting.VendorPackageSymbolPath;
2288
                double x = vendorPackage.SPPID.ORIGINAL_X;
2289
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2290

    
2291
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2292
                if (symbol != null)
2293
                {
2294
                    symbol.Commit();
2295
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2296
                }
2297

    
2298
                ReleaseCOMObjects(symbol);
2299
                symbol = null;
2300
            }
2301
        }
2302

    
2303
        private void GraphicModeling(Graphic graphic)
2304
        {
2305
            Ingr.RAD2D.SmartFrame2d borderFrame = radApp.ActiveDocument.ActiveSheet.SmartFrames2d[0];
2306
            string styleName = "SFStyleConverter";
2307
            string projectPah = Settings.Default.ProjectPath;
2308
            string graphicDirectory = Path.Combine(projectPah, "graphic");
2309
            string filePath = Path.Combine(graphicDirectory, string.Format("{0}.igr", graphic.NAME));
2310
            if (!File.Exists(filePath)) return;
2311

    
2312
            int styleCount = radApp.ActiveDocument.SmartFrame2dStyles.Count(c => c.Name.StartsWith(styleName));
2313
            styleName = string.Format("{0}_{1}", styleName, styleCount);
2314
            Ingr.RAD2D.SmartFrame2dStyle StyleConverter = radApp.ActiveDocument.SmartFrame2dStyles.Add(styleName, "");
2315

    
2316
            Ingr.RAD2D.SmartFrame2d smartFrame = radApp.ActiveDocument.ActiveSheet.SmartFrames2d.AddBy2Points(styleName, 0.01, 0.01, 0.1, 0.1, false, filePath);
2317
            smartFrame.BorderVisible = false;
2318
            smartFrame.SetLayerDisplay("default", true);
2319

    
2320
            double oMinx = 0, oMinY = 0, oMaxX = 0, oMaxY = 0;
2321
            smartFrame.Range(out oMinx, out oMinY, out oMaxX, out oMaxY);
2322
            double cWidth = oMaxX - oMinx;
2323
            double cHeight = oMaxY - oMinY;
2324
            double height = Math.Abs(graphic.SPPIDGraphicLocation.Y2 - graphic.SPPIDGraphicLocation.Y1);
2325
            double width = Math.Abs(graphic.SPPIDGraphicLocation.X2 - graphic.SPPIDGraphicLocation.X1);
2326
            double scaleFactor = width / cWidth;
2327
            smartFrame.ScaleFactor = scaleFactor;
2328
            smartFrame.SetOrigin(graphic.SPPIDGraphicLocation.X1, graphic.SPPIDGraphicLocation.Y1);
2329
        }
2330

    
2331
        /// <summary>
2332
        /// 첫 진입점
2333
        /// </summary>
2334
        /// <param name="symbol"></param>
2335
        private void SymbolModelingBySymbol(Symbol symbol)
2336
        {
2337
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2338
            List<object> endObjects = new List<object>();
2339
            endObjects.Add(symbol);
2340

    
2341
            // 심볼에 연결되어 있는 항목들을 모델링한다
2342
            foreach (var connector in symbol.CONNECTORS)
2343
            {
2344
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2345
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2346
                {
2347
                    endObjects.Add(connItem);
2348
                    if (connItem.GetType() == typeof(Symbol))
2349
                    {
2350
                        Symbol connSymbol = connItem as Symbol;
2351
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2352
                        {
2353
                            SymbolModeling(connSymbol, symbol);
2354
                        }
2355
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2356
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2357
                    }
2358
                    else if (connItem.GetType() == typeof(Line))
2359
                    {
2360
                        Line connLine = connItem as Line;
2361
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2362
                    }
2363
                }
2364
            }
2365
        }
2366

    
2367
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2368
        {
2369
            foreach (var connector in symbol.CONNECTORS)
2370
            {
2371
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2372
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2373
                {
2374
                    if (!endObjects.Contains(connItem))
2375
                    {
2376
                        endObjects.Add(connItem);
2377
                        if (connItem.GetType() == typeof(Symbol))
2378
                        {
2379
                            Symbol connSymbol = connItem as Symbol;
2380
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2381
                            {
2382
                                SymbolModeling(connSymbol, symbol);
2383
                            }
2384
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2385
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2386
                        }
2387
                        else if (connItem.GetType() == typeof(Line))
2388
                        {
2389
                            Line connLine = connItem as Line;
2390
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2391
                        }
2392
                    }
2393
                }
2394
            }
2395
        }
2396

    
2397
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2398
        {
2399
            foreach (var connector in line.CONNECTORS)
2400
            {
2401
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2402
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2403
                {
2404
                    if (!endObjects.Contains(connItem))
2405
                    {
2406
                        endObjects.Add(connItem);
2407
                        if (connItem.GetType() == typeof(Symbol))
2408
                        {
2409
                            Symbol connSymbol = connItem as Symbol;
2410
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2411
                            {
2412
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2413
                                int branchCount = 0;
2414
                                if (connLine != null)
2415
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2416

    
2417
                                List<Symbol> group = new List<Symbol>();
2418
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2419
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2420
                                List<Symbol> endModelingGroup = new List<Symbol>();
2421
                                if (priority != null)
2422
                                {
2423
                                    SymbolGroupModeling(priority, group);
2424

    
2425
                                    // Range 겹치는지 확인해야함
2426
                                    double[] prevRange = null;
2427
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2428
                                    double[] groupRange = null;
2429
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2430

    
2431
                                    double distanceX = 0;
2432
                                    double distanceY = 0;
2433
                                    bool overlapX = false;
2434
                                    bool overlapY = false;
2435
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2436
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2437
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2438
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2439
                                    {
2440
                                        RemoveSymbol(group);
2441
                                        foreach (var _temp in group)
2442
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2443

    
2444
                                        SymbolGroupModeling(priority, group);
2445
                                    }
2446
                                    else if (branchCount > 0)
2447
                                    {
2448
                                        LMConnector _connector = JustLineModeling(connLine);
2449
                                        if (_connector != null)
2450
                                        {
2451
                                            double distance = GetConnectorDistance(_connector);
2452
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2453
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2454
                                            _connector.Commit();
2455
                                            ReleaseCOMObjects(_connector);
2456
                                            _connector = null;
2457
                                            if (cellCount < branchCount + 1)
2458
                                            {
2459
                                                int moveCount = branchCount - cellCount;
2460
                                                RemoveSymbol(group);
2461
                                                foreach (var _temp in group)
2462
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2463

    
2464
                                                SymbolGroupModeling(priority, group);
2465
                                            }
2466
                                        }
2467
                                    }
2468
                                }
2469
                                else
2470
                                {
2471
                                    SymbolModeling(connSymbol, null);
2472
                                    // Range 겹치는지 확인해야함
2473
                                    double[] prevRange = null;
2474
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2475
                                    double[] connRange = null;
2476
                                    GetSPPIDSymbolRange(connSymbol, ref connRange, bForGraphic: true);
2477

    
2478
                                    double distanceX = 0;
2479
                                    double distanceY = 0;
2480
                                    bool overlapX = false;
2481
                                    bool overlapY = false;
2482
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2483
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2484
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2485
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2486
                                    {
2487
                                        RemoveSymbol(connSymbol);
2488
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2489

    
2490
                                        SymbolModeling(connSymbol, null);
2491
                                    }
2492
                                    else if (branchCount > 0)
2493
                                    {
2494
                                        LMConnector _connector = JustLineModeling(connLine);
2495
                                        if (_connector != null)
2496
                                        {
2497
                                            double distance = GetConnectorDistance(_connector);
2498
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2499
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2500
                                            _connector.Commit();
2501
                                            ReleaseCOMObjects(_connector);
2502
                                            _connector = null;
2503
                                            if (cellCount < branchCount + 1)
2504
                                            {
2505
                                                int moveCount = branchCount - cellCount;
2506
                                                RemoveSymbol(group);
2507
                                                foreach (var _temp in group)
2508
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2509

    
2510
                                                SymbolGroupModeling(priority, group);
2511
                                            }
2512
                                        }
2513
                                    }
2514
                                }
2515
                            }
2516
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2517
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2518
                        }
2519
                        else if (connItem.GetType() == typeof(Line))
2520
                        {
2521
                            Line connLine = connItem as Line;
2522
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2523
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2524
                        }
2525
                    }
2526
                }
2527
            }
2528
        }
2529

    
2530
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2531
        {
2532
            List<Symbol> endModelingGroup = new List<Symbol>();
2533
            SymbolModeling(firstSymbol, null);
2534
            endModelingGroup.Add(firstSymbol);
2535
            while (endModelingGroup.Count != group.Count)
2536
            {
2537
                foreach (var _symbol in group)
2538
                {
2539
                    if (!endModelingGroup.Contains(_symbol))
2540
                    {
2541
                        foreach (var _connector in _symbol.CONNECTORS)
2542
                        {
2543
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2544
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2545
                            {
2546
                                SymbolModeling(_symbol, _connSymbol);
2547
                                endModelingGroup.Add(_symbol);
2548
                                break;
2549
                            }
2550
                        }
2551
                    }
2552
                }
2553
            }
2554
        }
2555

    
2556
        /// <summary>
2557
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2558
        /// </summary>
2559
        /// <param name="childSymbol"></param>
2560
        /// <param name="parentSymbol"></param>
2561
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2562
        {
2563
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2564
            double x1 = 0;
2565
            double x2 = 0;
2566
            double y1 = 0;
2567
            double y2 = 0;
2568
            symbol2d.Range(out x1, out y1, out x2, out y2);
2569

    
2570
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2571
            if (_LMSymbol != null)
2572
            {
2573
                _LMSymbol.Commit();
2574
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2575
                foreach (var item in childSymbol.ChildSymbols)
2576
                    CreateChildSymbol(item, _LMSymbol, parent);
2577
            }
2578

    
2579
            ReleaseCOMObjects(_LMSymbol);
2580
        }
2581
        double index = 0;
2582
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2583
        {
2584
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2585
                return;
2586

    
2587
            List<Line> group = new List<Line>();
2588
            GetConnectedLineGroup(line, group);
2589
            if (!BranchLines.Contains(line))
2590
                LineCoordinateCorrection(group);
2591

    
2592
            for (int i = 0; i < group.Count; i++)
2593
            {
2594
                string targetModelItemId = null;
2595
                var currentLine = group[i];
2596

    
2597
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(currentLine))
2598
                {
2599
                    for (int j = i; j < group.Count; j++)
2600
                    {
2601
                        var brachLine = group[j];
2602
                        if (!BranchLines.Contains(brachLine))
2603
                            BranchLines.Add(brachLine);
2604
                    }
2605
                    break;
2606
                }
2607
                if (currentLine.CONNECTORS[0].ConnectedObject != null
2608
                    && currentLine.CONNECTORS[0].ConnectedObject.GetType() == typeof(Line)
2609
                    && string.IsNullOrEmpty(((Line)currentLine.CONNECTORS[0].ConnectedObject).SPPID.ModelItemId)
2610
                    && currentLine.TRYCOUNT < 100)
2611
                {
2612
                    currentLine.TRYCOUNT++;
2613
                    break;
2614
                }
2615

    
2616
                bool diagonal = false;
2617
                if (currentLine.SlopeType != SlopeType.HORIZONTAL && currentLine.SlopeType != SlopeType.VERTICAL)
2618
                    diagonal = true;
2619
                _LMAItem lMAItem = _placement.PIDCreateItem(currentLine.SPPID.MAPPINGNAME);
2620
                if (currentLine.SPPID.MAPPINGNAME != @"\Piping\Routing\Process Lines\Secondary Piping.sym")
2621
                {
2622
                    currentLine.SPPID.MAPPINGNAME = currentLine.SPPID.MAPPINGNAME;
2623
                }
2624
                LMSymbol lMSymbolStart = null;
2625
                LMSymbol lMSymbolEnd = null;
2626
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2627
                foreach (var connector in currentLine.CONNECTORS)
2628
                {
2629
                    double x = 0;
2630
                    double y = 0;
2631
                    GetTargetLineConnectorPoint(connector, currentLine, ref x, ref y);
2632
                    if (connector.ConnectedObject == null)
2633
                        placeRunInputs.AddPoint(x, y);
2634
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2635
                    {
2636
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2637
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == currentLine), targetSymbol, ref x, ref y);
2638
                        if (currentLine.CONNECTORS.IndexOf(connector) == 0)
2639
                        {
2640
                            lMSymbolStart = GetTargetSymbol(targetSymbol, currentLine);
2641
                            if (lMSymbolStart != null)
2642
                            {
2643
                                foreach (LMConnector item in lMSymbolStart.Connect1Connectors)
2644
                                {
2645
                                    if (item.Attributes["ItemStatus"].get_Value() == "Active" && item.Attributes["IsZeroLength"].get_Value() == "True")
2646
                                    {
2647
                                        targetModelItemId = item.ModelItemID;
2648
                                        break;
2649
                                    }
2650
                                }
2651
                                foreach (LMConnector item in lMSymbolStart.Connect2Connectors)
2652
                                {
2653
                                    if (item.Attributes["ItemStatus"].get_Value() == "Active" && item.Attributes["IsZeroLength"].get_Value() == "True")
2654
                                    {
2655
                                        targetModelItemId = item.ModelItemID;
2656
                                        break;
2657
                                    }
2658
                                }
2659

    
2660
                                placeRunInputs.AddSymbolTarget(lMSymbolStart, x, y, diagonal);
2661
                            }
2662
                            else
2663
                                placeRunInputs.AddPoint(x, y);
2664
                        }
2665
                        else
2666
                        {
2667
                            lMSymbolEnd = GetTargetSymbol(targetSymbol, currentLine);
2668
                            if (lMSymbolEnd != null)
2669
                                placeRunInputs.AddSymbolTarget(lMSymbolEnd, x, y, diagonal);
2670
                            else
2671
                                placeRunInputs.AddPoint(x, y);
2672
                        }
2673
                    }
2674
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2675
                    {
2676
                        Line targetLine = connector.ConnectedObject as Line;
2677
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2678
                        {
2679
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(currentLine, targetLine, ref x, ref y);
2680
                            if (targetConnector != null)
2681
                            {
2682
                                if (targetLine.SlopeType != SlopeType.HORIZONTAL && targetLine.SlopeType != SlopeType.VERTICAL)
2683
                                    placeRunInputs.AddConnectorTarget(targetConnector, x, y, true);
2684
                                else
2685
                                    placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2686
                                ChangeLineSPPIDCoordinateByConnector(currentLine, targetLine, x, y, false);
2687
                            }
2688
                            else
2689
                            {
2690
                                placeRunInputs.AddPoint(x, y);
2691
                                ChangeLineSPPIDCoordinateByConnector(currentLine, targetLine, x, y, false);
2692
                            }
2693
                        }
2694
                        else
2695
                        {
2696
                            if (currentLine.CONNECTORS.IndexOf(connector) == 0)
2697
                            {
2698
                                index += 0.01;
2699
                                if (currentLine.SlopeType == SlopeType.HORIZONTAL)
2700
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2701
                                else if (currentLine.SlopeType == SlopeType.VERTICAL)
2702
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2703
                                else
2704
                                {
2705
                                    Line nextLine = currentLine.CONNECTORS[0].ConnectedObject as Line;
2706
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2707
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2708
                                    else
2709
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2710
                                }
2711
                            }
2712

    
2713
                            placeRunInputs.AddPoint(x, y);
2714

    
2715
                            if (currentLine.CONNECTORS.IndexOf(connector) == 1)
2716
                            {
2717
                                index += 0.01;
2718
                                if (currentLine.SlopeType == SlopeType.HORIZONTAL)
2719
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2720
                                else if (currentLine.SlopeType == SlopeType.VERTICAL)
2721
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2722
                                else
2723
                                {
2724
                                    Line nextLine = currentLine.CONNECTORS[1].ConnectedObject as Line;
2725
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2726
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2727
                                    else
2728
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2729
                                }
2730
                            }
2731
                        }
2732
                    }
2733
                    else
2734
                        placeRunInputs.AddPoint(x, y);
2735
                }
2736

    
2737
                LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
2738
                if (lMConnector != null)
2739
                {
2740
                    lMConnector.Commit();
2741
                    if (!string.IsNullOrWhiteSpace(targetModelItemId))
2742
                    {
2743
                        LMModelItem modelItem1 = dataSource.GetModelItem(targetModelItemId);
2744
                        LMModelItem modelItem2 = dataSource.GetModelItem(lMConnector.ModelItemID);
2745
                        _LMAItem item1 = modelItem1.AsLMAItem();
2746
                        _LMAItem item2 = modelItem2.AsLMAItem();
2747
                        _placement.PIDJoinRuns(item1, item2);
2748
                        item1.Commit();
2749
                        item2.Commit();
2750
                        ReleaseCOMObjects(item1);
2751
                        ReleaseCOMObjects(item2);
2752
                        ReleaseCOMObjects(modelItem1);
2753
                        ReleaseCOMObjects(modelItem2);
2754
                    }
2755

    
2756
                    currentLine.SPPID.ModelItemId = lMConnector.ModelItemID;
2757

    
2758
                    bool bRemodelingStart = false;
2759
                    if (lMSymbolStart != null)
2760
                        NeedReModeling(currentLine, lMSymbolStart, ref bRemodelingStart);
2761
                    bool bRemodelingEnd = false;
2762
                    if (lMSymbolEnd != null)
2763
                        NeedReModeling(currentLine, lMSymbolEnd, ref bRemodelingEnd);
2764

    
2765
                    if (bRemodelingStart || bRemodelingEnd)
2766
                        ReModelingLine(currentLine, lMConnector, lMSymbolStart, lMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2767

    
2768
                    FlowMarkModeling(currentLine);
2769

    
2770
                    ReleaseCOMObjects(lMConnector);
2771

    
2772
                    LMModelItem modelItem = dataSource.GetModelItem(currentLine.SPPID.ModelItemId);
2773
                    if (modelItem != null)
2774
                    {
2775
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2776
                        if (attribute != null)
2777
                            attribute.set_Value("End 1 is upstream (Inlet)");
2778
                        modelItem.Commit();
2779
                    }
2780
                    ReleaseCOMObjects(modelItem);
2781
                    modelItem = null;
2782
                }
2783
                else if (!isBranchModeling)
2784
                {
2785
                    Log.Write("Main Line Modeling : " + currentLine.UID);
2786
                }
2787

    
2788
                List<object> removeLines = currentLine.CONNECTORS.FindAll(x =>
2789
                x.ConnectedObject != null &&
2790
                x.ConnectedObject.GetType() == typeof(Line) &&
2791
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2792
                .Select(x => x.ConnectedObject)
2793
                .ToList();
2794

    
2795
                foreach (var item in removeLines)
2796
                    RemoveLineForModeling(item as Line);
2797

    
2798
                ReleaseCOMObjects(lMAItem);
2799
                lMAItem = null;
2800
                ReleaseCOMObjects(placeRunInputs);
2801
                placeRunInputs = null;
2802
                ReleaseCOMObjects(lMSymbolStart);
2803
                lMSymbolStart = null;
2804
                ReleaseCOMObjects(lMSymbolEnd);
2805
                lMSymbolEnd = null;
2806
            }
2807
        }
2808

    
2809
        private LMConnector JustLineModeling(Line line)
2810
        {
2811
            bool diagonal = false;
2812
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2813
                diagonal = true;
2814
            _LMAItem lMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2815
            LMSymbol lMSymbolStart = null;
2816
            LMSymbol lMSymbolEnd = null;
2817
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2818
            foreach (var connector in line.CONNECTORS)
2819
            {
2820
                double x = 0;
2821
                double y = 0;
2822
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2823
                if (connector.ConnectedObject == null)
2824
                {
2825
                    placeRunInputs.AddPoint(x, y);
2826
                }
2827
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2828
                {
2829
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2830
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2831
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2832
                    {
2833
                        lMSymbolStart = GetTargetSymbol(targetSymbol, line);
2834
                        if (lMSymbolStart != null)
2835
                            placeRunInputs.AddSymbolTarget(lMSymbolStart, x, y, diagonal);
2836
                        else
2837
                            placeRunInputs.AddPoint(x, y);
2838
                    }
2839
                    else
2840
                    {
2841
                        lMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2842
                        if (lMSymbolEnd != null)
2843
                            placeRunInputs.AddSymbolTarget(lMSymbolEnd, x, y, diagonal);
2844
                        else
2845
                            placeRunInputs.AddPoint(x, y);
2846
                    }
2847
                }
2848
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2849
                {
2850
                    Line targetLine = connector.ConnectedObject as Line;
2851
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2852
                    {
2853
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2854
                        if (targetConnector != null)
2855
                        {
2856
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2857
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2858
                        }
2859
                        else
2860
                        {
2861
                            placeRunInputs.AddPoint(x, y);
2862
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2863
                        }
2864
                    }
2865
                    else
2866
                        placeRunInputs.AddPoint(x, y);
2867
                }
2868
            }
2869

    
2870
            LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
2871
            if (lMConnector != null)
2872
                lMConnector.Commit();
2873

    
2874
            ReleaseCOMObjects(lMAItem);
2875
            lMAItem = null;
2876
            ReleaseCOMObjects(placeRunInputs);
2877
            placeRunInputs = null;
2878
            ReleaseCOMObjects(lMSymbolStart);
2879
            lMSymbolStart = null;
2880
            ReleaseCOMObjects(lMSymbolEnd);
2881
            lMSymbolEnd = null;
2882

    
2883
            return lMConnector;
2884
        }
2885

    
2886
        private void RemoveLineForModeling(Line line)
2887
        {
2888
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2889
            if (modelItem != null)
2890
            {
2891
                foreach (LMRepresentation rep in modelItem.Representations)
2892
                {
2893
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2894
                    {
2895
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2896
                        dynamic OID = rep.get_GraphicOID().ToString();
2897
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2898
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2899
                        int verticesCount = lineStringGeometry.VertexCount;
2900
                        double[] vertices = null;
2901
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2902
                        for (int i = 0; i < verticesCount; i++)
2903
                        {
2904
                            double x = 0;
2905
                            double y = 0;
2906
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2907
                            if (verticesCount == 2 && (x < 0 || y < 0))
2908
                                _placement.PIDRemovePlacement(rep);
2909
                        }
2910
                        ReleaseCOMObjects(_LMConnector);
2911
                    }
2912
                }
2913

    
2914
                ReleaseCOMObjects(modelItem);
2915
            }
2916
        }
2917

    
2918
        private void RemoveLine(Line line)
2919
        {
2920
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2921
            if (modelItem != null)
2922
            {
2923
                foreach (LMRepresentation rep in modelItem.Representations)
2924
                {
2925
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2926
                        _placement.PIDRemovePlacement(rep);
2927
                }
2928
                ReleaseCOMObjects(modelItem);
2929
            }
2930
            line.SPPID.ModelItemId = null;
2931
        }
2932

    
2933
        private void GetConnectedLineGroup(Line line, List<Line> group)
2934
        {
2935
            if (!group.Contains(line))
2936
                group.Add(line);
2937

    
2938
            foreach (var connector in line.CONNECTORS)
2939
            {
2940
                if (connector.ConnectedObject != null &&
2941
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2942
                    !group.Contains(connector.ConnectedObject) &&
2943
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2944
                {
2945
                    Line connLine = connector.ConnectedObject as Line;
2946
                    if (line.CONNECTORS.IndexOf(connector) == 0
2947
                    && (!SPPIDUtil.IsBranchLine(connLine, line)))
2948
                    {
2949

    
2950
                        group.Insert(group.IndexOf(line), connLine);
2951
                        GetConnectedLineGroup(connLine, group);
2952
                    }
2953
                    else if (line.CONNECTORS.IndexOf(connector) == 1 && !SPPIDUtil.IsBranchLine(connLine, line))
2954
                    {
2955
                        group.Add(connLine);
2956
                        GetConnectedLineGroup(connLine, group);
2957
                    }
2958
                }
2959
            }
2960
        }
2961

    
2962
        private void LineCoordinateCorrection(List<Line> group)
2963
        {
2964
            // 순서대로 전 Item 기준 정렬
2965
            LineCoordinateCorrectionByStart(group);
2966

    
2967
            // 역으로 심볼이 있을 경우 좌표 보정
2968
            LineCoordinateCorrectionForLastLine(group);
2969
        }
2970

    
2971
        private void LineCoordinateCorrectionByStart(List<Line> group)
2972
        {
2973
            for (int i = 0; i < group.Count; i++)
2974
            {
2975
                Line line = group[i];
2976
                if (i == 0)
2977
                {
2978
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2979
                    if (symbolConnector != null)
2980
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2981
                }
2982
                else if (i != 0)
2983
                {
2984
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2985
                }
2986
            }
2987
        }
2988

    
2989
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2990
        {
2991
            Line checkLine = group[group.Count - 1];
2992
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2993
            if (lastSymbolConnector != null)
2994
            {
2995
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2996
                for (int i = group.Count - 2; i >= 0; i--)
2997
                {
2998
                    Line refLine = group[i + 1];
2999
                    Line changeline = group[i];
3000
                    LineCoordinateCorrectionByConnItem(changeline, refLine);
3001
                }
3002
            }
3003
        }
3004

    
3005
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
3006
        {
3007
            double x = 0;
3008
            double y = 0;
3009
            if (connItem.GetType() == typeof(Symbol))
3010
            {
3011
                Symbol targetSymbol = connItem as Symbol;
3012
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
3013
                if (targetConnector != null)
3014
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
3015
                else
3016
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
3017
            }
3018
            else if (connItem.GetType() == typeof(Line))
3019
            {
3020
                Line targetLine = connItem as Line;
3021
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
3022
            }
3023

    
3024
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
3025
        }
3026
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
3027
        {
3028
            bool isReverseX = line.SPPID.END_X - line.SPPID.START_X < 0;
3029
            bool isReverseY = line.SPPID.END_Y - line.SPPID.START_Y < 0;
3030
            double minLength = GridSetting.GetInstance().Length * 0.5;
3031
            double minLengthX = minLength * (!isReverseX ? 1 : -1);
3032
            double minLengthY = minLength * (!isReverseY ? 1 : -1);
3033

    
3034
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3035
            int index = line.CONNECTORS.IndexOf(connector);
3036
            if (index == 0)
3037
            {
3038
                line.SPPID.START_X = x;
3039
                line.SPPID.START_Y = y;
3040
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
3041
                {
3042
                    line.SPPID.END_Y = y;
3043
                    // START_X가 END_X 값을 벗어날 경우 END_X 값 보정
3044
                    if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= minLength)
3045
                    {
3046
                        line.SPPID.END_X = line.SPPID.START_X + minLengthX;
3047
                    }
3048
                }
3049
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
3050
                {
3051
                    line.SPPID.END_X = x;
3052
                    // START_Y가 END_Y 값을 벗어날 경우 END_Y 값 보정
3053
                    if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= minLength)
3054
                    {
3055
                        line.SPPID.END_Y = line.SPPID.START_Y + minLengthY;
3056
                    }
3057
                }
3058
            }
3059
            else
3060
            {
3061
                line.SPPID.END_X = x;
3062
                line.SPPID.END_Y = y;
3063
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
3064
                {
3065
                    line.SPPID.START_Y = y;
3066
                    // END_X가 START_X 값을 벗어날 경우 START_X 값 보정
3067
                    if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= minLength)
3068
                    {
3069
                        line.SPPID.START_X = line.SPPID.END_X - minLengthX;
3070
                    }
3071
                }
3072
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
3073
                {
3074
                    line.SPPID.START_X = x;
3075
                    // END_Y가 START_Y 값을 벗어날 경우 START_Y 값 보정
3076
                    if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= minLength)
3077
                    {
3078
                        line.SPPID.START_Y = line.SPPID.END_Y - minLengthY;
3079
                    }
3080
                }
3081
            }
3082
        }
3083

    
3084
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
3085
        {
3086
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3087
            int index = line.CONNECTORS.IndexOf(connector);
3088
            if (index == 0)
3089
            {
3090
                line.SPPID.START_X = x;
3091
                if (line.SlopeType == SlopeType.VERTICAL)
3092
                    line.SPPID.END_X = x;
3093
            }
3094
            else
3095
            {
3096
                line.SPPID.END_X = x;
3097
                if (line.SlopeType == SlopeType.VERTICAL)
3098
                    line.SPPID.START_X = x;
3099
            }
3100
        }
3101

    
3102
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
3103
        {
3104
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3105
            int index = line.CONNECTORS.IndexOf(connector);
3106
            if (index == 0)
3107
            {
3108
                line.SPPID.START_Y = y;
3109
                if (line.SlopeType == SlopeType.HORIZONTAL)
3110
                    line.SPPID.END_Y = y;
3111
            }
3112
            else
3113
            {
3114
                line.SPPID.END_Y = y;
3115
                if (line.SlopeType == SlopeType.HORIZONTAL)
3116
                    line.SPPID.START_Y = y;
3117
            }
3118
        }
3119

    
3120
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
3121
        {
3122
            if (symbol != null)
3123
            {
3124
                string repID = symbol.AsLMRepresentation().Id;
3125
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
3126
                string lineUID = line.UID;
3127

    
3128
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
3129
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
3130
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
3131

    
3132
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
3133
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
3134
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
3135

    
3136
                if (startSpecBreak != null || startEndBreak != null)
3137
                    result = true;
3138
            }
3139
        }
3140

    
3141
        /// <summary>
3142
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
3143
        /// </summary>
3144
        /// <param name="lines"></param>
3145
        /// <param name="prevLMConnector"></param>
3146
        /// <param name="startSymbol"></param>
3147
        /// <param name="endSymbol"></param>
3148
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
3149
        {
3150
            string symbolPath = string.Empty;
3151
            #region get symbol path
3152
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
3153
            symbolPath = GetSPPIDFileName(modelItem);
3154
            ReleaseCOMObjects(modelItem);
3155
            #endregion
3156
            bool diagonal = false;
3157
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
3158
                diagonal = true;
3159
            _LMAItem lMAItem = _placement.PIDCreateItem(symbolPath);
3160
            LMConnector newConnector = null;
3161
            LMConnector newFirstConnector = null;
3162
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
3163
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3164
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3165
            int verticesCount = lineStringGeometry.VertexCount;
3166
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3167

    
3168
            List<double[]> vertices = new List<double[]>();
3169
            for (int i = 1; i <= verticesCount; i++)
3170
            {
3171
                double x = 0;
3172
                double y = 0;
3173
                lineStringGeometry.GetVertex(i, ref x, ref y);
3174
                vertices.Add(new double[] { x, y });
3175
            }
3176

    
3177
            for (int i = 0; i < vertices.Count; i++)
3178
            {
3179
                double[] points = vertices[i];
3180
                // 시작 심볼이 있고 첫번째 좌표일 때
3181
                if (startSymbol != null && i == 0)
3182
                {
3183
                    if (bStart)
3184
                    {
3185
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
3186
                        if (slopeType == SlopeType.HORIZONTAL)
3187
                            placeRunInputs.AddPoint(points[0], -0.1);
3188
                        else if (slopeType == SlopeType.VERTICAL)
3189
                            placeRunInputs.AddPoint(-0.1, points[1]);
3190
                        else
3191
                            placeRunInputs.AddPoint(points[0], -0.1);
3192

    
3193
                        placeRunInputs.AddPoint(points[0], points[1]);
3194
                    }
3195
                    else
3196
                    {
3197
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
3198
                    }
3199
                }
3200
                // 마지막 심볼이 있고 마지막 좌표일 때
3201
                else if (endSymbol != null && i == vertices.Count - 1)
3202
                {
3203
                    if (bEnd)
3204
                    {
3205
                        _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3206
                        PlaceRunInputs placeFirstRunInputs = new PlaceRunInputs();
3207

    
3208
                        placeFirstRunInputs.AddPoint(points[0], points[1]);
3209
                        placeFirstRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3210

    
3211
                        string otherSymbolPath = symbolPath;
3212
                        Symbol symbolDef = document.SYMBOLS.FirstOrDefault(f => f.SPPID.RepresentationId == endSymbol.AsLMRepresentation().Id);
3213
                        if (symbolDef != null)
3214
                        {
3215
                            Connector otherConn = symbolDef.CONNECTORS.FirstOrDefault(f => f.ConnectedObject != null && f.ConnectedObject.GetType() == typeof(Line) && ((Line)f.ConnectedObject).UID != line.UID);
3216
                            if (otherConn != null)
3217
                            {
3218
                                otherSymbolPath = ((Line)otherConn.ConnectedObject).SPPID.MAPPINGNAME;
3219
                            }
3220
                        }
3221

    
3222
                        _LMAItem lMAFirstItem = _placement.PIDCreateItem(otherSymbolPath);
3223
                        newFirstConnector = _placement.PIDPlaceRun(lMAFirstItem, placeFirstRunInputs);
3224
                        newFirstConnector.Commit();
3225

    
3226
                        placeRunInputs.AddConnectorTarget(newFirstConnector, points[0], points[1], diagonal);
3227
                        ReleaseCOMObjects(placeFirstRunInputs);
3228
                        ReleaseCOMObjects(lMAFirstItem);
3229
                    }
3230
                    else
3231
                    {
3232
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3233
                    }
3234
                }
3235
                // 첫번째이며 시작 심볼이 아니고 Connector일 경우
3236
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
3237
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
3238
                // 마지막이며 마지막 심볼이 아니고 Connector일 경우
3239
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
3240
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
3241
                else
3242
                    placeRunInputs.AddPoint(points[0], points[1]);
3243
            }
3244

    
3245
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3246
            newConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3247

    
3248
            ReleaseCOMObjects(placeRunInputs);
3249
            ReleaseCOMObjects(lMAItem);
3250
            ReleaseCOMObjects(modelItem);
3251

    
3252
            if (newConnector != null)
3253
            {
3254
                newConnector.Commit();
3255
                if (startSymbol != null && bStart)
3256
                {
3257
                    lMAItem = _placement.PIDCreateItem(symbolPath);
3258
                    placeRunInputs = new PlaceRunInputs();
3259
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
3260
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
3261
                    LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3262
                    if (lMConnector != null)
3263
                    {
3264
                        lMConnector.Commit();
3265
                        RemoveConnectorForReModelingLine(newConnector);
3266
                        ReleaseCOMObjects(lMConnector);
3267
                    }
3268
                    ReleaseCOMObjects(placeRunInputs);
3269
                    ReleaseCOMObjects(lMAItem);
3270
                }
3271

    
3272
                if (endSymbol != null && bEnd)
3273
                {
3274
                    ReleaseCOMObjects(newFirstConnector);
3275
                    ReleaseCOMObjects(placeRunInputs);
3276
                    ReleaseCOMObjects(lMAItem);
3277
                }
3278

    
3279
                line.SPPID.ModelItemId = newConnector.ModelItemID;
3280
                ReleaseCOMObjects(newConnector);
3281
            }
3282

    
3283
            ReleaseCOMObjects(modelItem);
3284
        }
3285

    
3286
        /// <summary>
3287
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
3288
        /// </summary>
3289
        /// <param name="connector"></param>
3290
        private void RemoveConnectorForReModelingLine(LMConnector connector)
3291
        {
3292
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
3293
            foreach (var item in dicVertices)
3294
            {
3295
                if (item.Value.Count == 2)
3296
                {
3297
                    bool result = false;
3298
                    foreach (var point in item.Value)
3299
                    {
3300
                        if (point[0] < 0 || point[1] < 0)
3301
                        {
3302
                            result = true;
3303
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
3304
                            break;
3305
                        }
3306
                    }
3307

    
3308
                    if (result)
3309
                        break;
3310
                }
3311
            }
3312
            foreach (var item in dicVertices)
3313
                ReleaseCOMObjects(item.Key);
3314
        }
3315

    
3316
        /// <summary>
3317
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
3318
        /// </summary>
3319
        /// <param name="symbol"></param>
3320
        /// <param name="line"></param>
3321
        /// <returns></returns>
3322
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
3323
        {
3324
            LMSymbol _LMSymbol = null;
3325
            foreach (var connector in symbol.CONNECTORS)
3326
            {
3327
                if (connector.CONNECTEDITEM == line.UID)
3328
                {
3329
                    if (connector.Index == 0)
3330
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3331
                    else
3332
                    {
3333
                        ChildSymbol child = null;
3334
                        foreach (var childSymbol in symbol.ChildSymbols)
3335
                        {
3336
                            if (childSymbol.Connectors.Contains(connector))
3337
                                child = childSymbol;
3338
                            else
3339
                                child = GetChildSymbolByConnector(childSymbol, connector);
3340

    
3341
                            if (child != null)
3342
                                break;
3343
                        }
3344

    
3345
                        if (child != null)
3346
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3347
                    }
3348

    
3349
                    break;
3350
                }
3351
            }
3352

    
3353
            return _LMSymbol;
3354
        }
3355

    
3356
        /// <summary>
3357
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3358
        /// </summary>
3359
        /// <param name="item"></param>
3360
        /// <param name="connector"></param>
3361
        /// <returns></returns>
3362
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3363
        {
3364
            foreach (var childSymbol in item.ChildSymbols)
3365
            {
3366
                if (childSymbol.Connectors.Contains(connector))
3367
                    return childSymbol;
3368
                else
3369
                    return GetChildSymbolByConnector(childSymbol, connector);
3370
            }
3371

    
3372
            return null;
3373
        }
3374

    
3375
        /// <summary>
3376
        /// EndBreak 모델링 메서드
3377
        /// </summary>
3378
        /// <param name="endBreak"></param>
3379
        private void EndBreakModeling(EndBreak endBreak)
3380
        {
3381
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3382
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3383

    
3384
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3385
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3386
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3387

    
3388
            if (targetLMConnector != null)
3389
            {
3390
                // LEADER Line 검사
3391
                bool leaderLine = false;
3392
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3393
                if (symbolMapping != null)
3394
                    leaderLine = symbolMapping.LEADERLINE;
3395

    
3396
                SegmentLocation location;
3397
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3398

    
3399
                Array array = null;
3400
                if (point != null)
3401
                    array = new double[] { 0, point[0], point[1] };
3402
                else
3403
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3404

    
3405
                LMLabelPersist _LmLabelPersist;
3406

    
3407
                Property property = endBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Freeze");
3408
                if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3409
                {
3410
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3411
                    if (_LmLabelPersist == null)
3412
                    {
3413
                        _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, IsLeaderVisible: leaderLine);
3414
                    }
3415
                }
3416
                else
3417
                {
3418
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3419
                    if (_LmLabelPersist == null)
3420
                    {
3421
                        _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, IsLeaderVisible: leaderLine);
3422
                    }
3423
                }
3424

    
3425
                if (_LmLabelPersist != null)
3426
                {
3427
                    _LmLabelPersist.Commit();
3428
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3429
                    if (_LmLabelPersist.ModelItemObject != null)
3430
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3431
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3432

    
3433
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3434

    
3435
                    // end break arrange
3436
                    if (property == null || string.IsNullOrEmpty(property.VALUE) || !property.VALUE.Equals("True"))
3437
                    {
3438
                        MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3439
                    }
3440

    
3441
                    ReleaseCOMObjects(_LmLabelPersist);
3442
                }
3443
                ReleaseCOMObjects(targetLMConnector);
3444
            }
3445
            else
3446
            {
3447
                Log.Write("End Break UID : " + endBreak.UID);
3448
                Log.Write("Can't find targetLMConnector");
3449
            }
3450
        }
3451

    
3452
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3453
        {
3454
            double x = 0, y = 0;
3455
            if (location.HasFlag(SegmentLocation.Up))
3456
                y = GridSetting.GetInstance().Length * 3;
3457
            else if (location.HasFlag(SegmentLocation.Down))
3458
                y = -GridSetting.GetInstance().Length * 3;
3459

    
3460
            if (location.HasFlag(SegmentLocation.Right))
3461
                x = GridSetting.GetInstance().Length * 3;
3462
            else if (location.HasFlag(SegmentLocation.Left))
3463
                x = -GridSetting.GetInstance().Length * 3;
3464

    
3465
            if (x != 0 || y != 0)
3466
            {
3467
                radApp.ActiveSelectSet.RemoveAll();
3468
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3469
                if (dependency != null)
3470
                {
3471
                    radApp.ActiveSelectSet.Add(dependency);
3472
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3473
                    transform.DefineByMove2d(x, y);
3474
                    radApp.ActiveSelectSet.Transform(transform, true);
3475
                    radApp.ActiveSelectSet.RemoveAll();
3476
                }
3477
            }
3478
        }
3479

    
3480
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3481
        {
3482
            string symbolPath = string.Empty;
3483
            #region get symbol path
3484
            if (string.IsNullOrEmpty(changeSymbolPath))
3485
            {
3486
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3487
                symbolPath = GetSPPIDFileName(modelItem);
3488
                ReleaseCOMObjects(modelItem);
3489
            }
3490
            else
3491
                symbolPath = changeSymbolPath;
3492

    
3493
            #endregion
3494

    
3495
            LMConnector newConnector = null;
3496
            dynamic OID = connector.get_GraphicOID().ToString();
3497
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3498
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3499
            int verticesCount = lineStringGeometry.VertexCount;
3500
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3501
            _LMAItem lMAItem = _placement.PIDCreateItem(symbolPath);
3502

    
3503
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3504
            {
3505
                double[] vertices = null;
3506
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3507
                double x = 0;
3508
                double y = 0;
3509
                lineStringGeometry.GetVertex(1, ref x, ref y);
3510

    
3511
                string flowDirection = string.Empty;
3512
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3513
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3514
                    flowDirection = flowAttribute.get_Value().ToString();
3515

    
3516
                if (flowDirection == "End 1 is downstream (Outlet)")
3517
                {
3518
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3519
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3520
                    flowDirection = "End 1 is upstream (Inlet)";
3521
                }
3522
                else
3523
                {
3524
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3525
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3526
                }
3527
                string oldModelItemId = connector.ModelItemID;
3528
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3529
                newConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3530
                newConnector.Commit();
3531
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3532
                if (!string.IsNullOrEmpty(flowDirection))
3533
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3534
                ReleaseCOMObjects(connector);
3535

    
3536
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3537
                {
3538
                    foreach (var repId in line.SPPID.Representations)
3539
                    {
3540
                        LMConnector _connector = dataSource.GetConnector(repId);
3541
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3542
                        {
3543
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3544
                            {
3545
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3546
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3547
                            }
3548
                        }
3549
                        ReleaseCOMObjects(_connector);
3550
                        _connector = null;
3551
                    }
3552
                }
3553
            }
3554

    
3555
            return newConnector;
3556
        }
3557

    
3558
        /// <summary>
3559
        /// SpecBreak Modeling 메서드
3560
        /// </summary>
3561
        /// <param name="specBreak"></param>
3562
        private void SpecBreakModeling(SpecBreak specBreak)
3563
        {
3564
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3565
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3566

    
3567
            if (upStreamObj != null &&
3568
                downStreamObj != null)
3569
            {
3570
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3571
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) &&
3572
                    targetLMConnector != null &&
3573
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3574
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3575

    
3576
                if (targetLMConnector != null)
3577
                {
3578
                    foreach (var attribute in specBreak.ATTRIBUTES)
3579
                    {
3580
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3581
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3582
                        {
3583
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3584
                            SegmentLocation location;
3585
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3586
                            Array array = null;
3587
                            if (point != null)
3588
                                array = new double[] { 0, point[0], point[1] };
3589
                            else
3590
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3591
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3592

    
3593
                            if (_LmLabelPersist != null)
3594
                            {
3595
                                _LmLabelPersist.Commit();
3596
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3597
                                if (_LmLabelPersist.ModelItemObject != null)
3598
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3599
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3600

    
3601
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3602

    
3603
                                // spec break arrange
3604
                                MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3605

    
3606
                                ReleaseCOMObjects(_LmLabelPersist);
3607
                            }
3608
                        }
3609
                    }
3610

    
3611
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3612
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3613
                    {
3614
                        // temp
3615
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3616
                    }
3617
                    ReleaseCOMObjects(targetLMConnector);
3618
                }
3619
                else
3620
                {
3621
                    Log.Write("Spec Break UID : " + specBreak.UID);
3622
                    Log.Write("Can't find targetLMConnector");
3623
                }
3624
            }
3625
        }
3626

    
3627
        private bool IsRhombus(LMLabelPersist labelPersist, out double x, out double y, out double radius)
3628
        {
3629
            bool result = false;
3630
            x = 0; y = 0; radius = 0;
3631

    
3632
            string oid = labelPersist.get_GraphicOID().ToString();
3633
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3634

    
3635
            if (dependency != null)
3636
            {
3637
                bool isLabel = false;
3638
                foreach (var attributes in dependency.AttributeSets)
3639
                {
3640
                    foreach (var attribute in attributes)
3641
                    {
3642
                        string name = attribute.Name;
3643
                        string value = attribute.GetValue().ToString();
3644
                        if (name == "DrawingItemType" && value == "LabelPersist")
3645
                        {
3646
                            isLabel = true;
3647
                            break;
3648
                        }
3649
                    }
3650
                }
3651
                if (isLabel)
3652
                {
3653
                    double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
3654
                    foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
3655
                    {
3656
                        if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLine2d)
3657
                        {
3658
                            Ingr.RAD2D.Line2d line2D = drawingObject as Ingr.RAD2D.Line2d;
3659

    
3660
                            double x1, y1, x2, y2;
3661
                            line2D.GetStartPoint(out x1, out y1);
3662
                            line2D.GetEndPoint(out x2, out y2);
3663
                            double tX1 = Math.Min(x1, x2), tY1 = Math.Min(y1, y2), tX2 = Math.Max(x1, x2), tY2 = Math.Max(y1, y2);
3664
                            if (minX > tX1)
3665
                                minX = tX1;
3666
                            if (minY > tY1)
3667
                                minY = tY1;
3668
                            if (maxX < tX2)
3669
                                maxX = tX2;
3670
                            if (maxY < tY2)
3671
                                maxY = tY2;
3672
                        }
3673
                    }
3674

    
3675
                    double width = Math.Abs(maxX - minX);
3676
                    double height = Math.Abs(maxY - minY);
3677
                    double ratio = width / height * 100;
3678
                    if (ratio > 99d && ratio < 101d)
3679
                    {
3680
                        result = true;
3681
                    }
3682
                    x = (maxX + minX) / 2d;
3683
                    y = (maxY + minY) / 2d;
3684
                    radius = width / 2d;
3685
                }
3686
            }
3687

    
3688
            return result;
3689
        }
3690

    
3691
        private void MoveSegmentBreak(string connectorID, LMLabelPersist labelPersist)
3692
        {
3693
            bool bFind = false;
3694
            double x, y, radius;
3695
            if (IsRhombus(labelPersist, out x, out y, out radius))
3696
            {
3697
                List<double[]> itemPoints = new List<double[]>();
3698
                LMConnector connector = dataSource.GetConnector(connectorID);
3699
                foreach (LMLabelPersist label in connector.LabelPersists)
3700
                {
3701
                    if (!"Active".Equals(label.get_ItemStatus()))
3702
                        continue;
3703

    
3704
                    if (!label.Id.Equals(labelPersist.Id))
3705
                    {
3706
                        double centerX, centerY, temp;
3707
                        if (IsRhombus(label, out centerX, out centerY, out temp))
3708
                        {
3709
                            bFind = true;
3710
                            itemPoints.Add(new double[] { centerX, centerY });
3711
                        }
3712
                    }
3713
                }
3714
                ReleaseCOMObjects(connector);
3715

    
3716

    
3717
                if (bFind)
3718
                {
3719
                    double[] startPoint = itemPoints.First();
3720
                    itemPoints.RemoveAt(0);
3721

    
3722
                    for (int i = 0; i < 8; i++)
3723
                    {
3724
                        double pointX = 0, pointY = 0;
3725
                        switch (i)
3726
                        {
3727
                            case 0:
3728
                                pointX = startPoint[0] + radius;
3729
                                pointY = startPoint[1] + radius;
3730
                                break;
3731
                            case 1:
3732
                                pointX = startPoint[0] + radius + radius;
3733
                                pointY = startPoint[1];
3734
                                break;
3735
                            case 2:
3736
                                pointX = startPoint[0] + radius;
3737
                                pointY = startPoint[1] - radius;
3738
                                break;
3739
                            case 3:
3740
                                pointX = startPoint[0];
3741
                                pointY = startPoint[1] - radius - radius;
3742
                                break;
3743
                            case 4:
3744
                                pointX = startPoint[0] - radius;
3745
                                pointY = startPoint[1] - radius;
3746
                                break;
3747
                            case 5:
3748
                                pointX = startPoint[0] - radius - radius;
3749
                                pointY = startPoint[1];
3750
                                break;
3751
                            case 6:
3752
                                pointX = startPoint[0] - radius;
3753
                                pointY = startPoint[1] + radius;
3754
                                break;
3755
                            case 7:
3756
                                pointX = startPoint[0];
3757
                                pointY = startPoint[1] + radius + radius;
3758
                                break;
3759
                            default:
3760
                                break;
3761
                        }
3762

    
3763
                        if (!ExistSegmentByPoint(pointX, pointY))
3764
                        {
3765
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
3766
                            if (dependency != null)
3767
                            {
3768
                                radApp.ActiveSelectSet.RemoveAll();
3769
                                radApp.ActiveSelectSet.Add(dependency);
3770
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3771
                                transform.DefineByMove2d(pointX - x, pointY - y);
3772
                                radApp.ActiveSelectSet.Transform(transform, true);
3773
                                radApp.ActiveSelectSet.RemoveAll();
3774
                            }
3775
                            break;
3776
                        }
3777
                    }
3778

    
3779
                    bool ExistSegmentByPoint(double pointX, double pointY)
3780
                    {
3781
                        bool result = false;
3782
                        foreach (var item in itemPoints)
3783
                        {
3784
                            double distance = SPPIDUtil.CalcPointToPointdDistance(item[0], item[1], pointX, pointY);
3785
                            if (Math.Truncate(distance * 1000000000d).Equals(0))
3786
                                result = true;
3787
                        }
3788
                        return result;
3789
                    }
3790
                }
3791
            }
3792

    
3793
            if (!bFind)
3794
                MoveSegmentBestLocation(labelPersist.get_GraphicOID().ToString(), new double[] { x - radius, y - radius, x + radius, y + radius }, itemRange);
3795
        }
3796

    
3797
        LMConnectors GetConnectors()
3798
        {
3799
            LMAFilter filter = new LMAFilter();
3800
            LMACriterion criterion1 = new LMACriterion();
3801
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3802
            criterion1.Operator = "=";
3803
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3804
            criterion1.Conjunctive = true;
3805
            filter.get_Criteria().Add(criterion1);
3806
            filter.ItemType = "Connector";
3807

    
3808
            LMACriterion criterion2 = new LMACriterion();
3809
            criterion2.SourceAttributeName = "ITEMSTATUS";
3810
            criterion2.Operator = "=";
3811
            criterion2.set_ValueAttribute("1");
3812
            criterion2.Conjunctive = true;
3813
            filter.get_Criteria().Add(criterion2);
3814

    
3815
            LMACriterion criterion3 = new LMACriterion();
3816
            criterion3.SourceAttributeName = "INSTOCKPILE";
3817
            criterion3.Operator = "=";
3818
            criterion3.set_ValueAttribute("1");
3819
            criterion3.Conjunctive = true;
3820
            filter.get_Criteria().Add(criterion3);
3821

    
3822
            LMConnectors items = new LMConnectors();
3823
            items.Collect(dataSource, Filter: filter);
3824

    
3825
            ReleaseCOMObjects(filter);
3826
            ReleaseCOMObjects(criterion1);
3827
            ReleaseCOMObjects(criterion2);
3828
            ReleaseCOMObjects(criterion3);
3829

    
3830
            return items;
3831
        }
3832
        LMSymbols GetSymbols()
3833
        {
3834
            LMAFilter filter = new LMAFilter();
3835
            LMACriterion criterion1 = new LMACriterion();
3836
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3837
            criterion1.Operator = "=";
3838
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3839
            criterion1.Conjunctive = true;
3840
            filter.get_Criteria().Add(criterion1);
3841
            filter.ItemType = "Symbol";
3842

    
3843
            LMACriterion criterion2 = new LMACriterion();
3844
            criterion2.SourceAttributeName = "ITEMSTATUS";
3845
            criterion2.Operator = "=";
3846
            criterion2.set_ValueAttribute("1");
3847
            criterion2.Conjunctive = true;
3848
            filter.get_Criteria().Add(criterion2);
3849

    
3850
            LMACriterion criterion3 = new LMACriterion();
3851
            criterion3.SourceAttributeName = "INSTOCKPILE";
3852
            criterion3.Operator = "=";
3853
            criterion3.set_ValueAttribute("1");
3854
            criterion3.Conjunctive = true;
3855
            filter.get_Criteria().Add(criterion3);
3856

    
3857
            LMSymbols items = new LMSymbols();
3858
            items.Collect(dataSource, Filter: filter);
3859

    
3860
            ReleaseCOMObjects(filter);
3861
            ReleaseCOMObjects(criterion1);
3862
            ReleaseCOMObjects(criterion2);
3863
            ReleaseCOMObjects(criterion3);
3864

    
3865
            return items;
3866
        }
3867

    
3868
        private void SetConnectorAndSymbolRange()
3869
        {
3870
            itemRange = new List<double[]>();
3871

    
3872
            LMConnectors connectors = GetConnectors();
3873
            foreach (LMConnector connector in connectors)
3874
            {
3875
                List<double[]> vertices = GetConnectorVertices(connector);
3876
                for (int i = 0; i < vertices.Count - 1; i++)
3877
                {
3878
                    double[] point1 = vertices[i];
3879
                    double[] point2 = vertices[i + 1];
3880
                    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]);
3881
                    double gap = 0.0001d;
3882
                    itemRange.Add(new double[] { x1 - gap, y1 - gap, x2 + gap, y2 + gap });
3883
                }
3884
                ReleaseCOMObjects(connector);
3885
            }
3886
            ReleaseCOMObjects(connectors);
3887

    
3888
            LMSymbols symbols = GetSymbols();
3889
            foreach (LMSymbol symbol in symbols)
3890
            {
3891
                string oid = symbol.get_GraphicOID().ToString();
3892
                DrawingObjectBase drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid];
3893
                if (drawingObject != null)
3894
                {
3895
                    double x1, y1, x2, y2;
3896
                    drawingObject.Range(out x1, out y1, out x2, out y2);
3897
                    itemRange.Add(new double[] { x1, y1, x2, y2 });
3898
                }
3899

    
3900
                ReleaseCOMObjects(symbol);
3901
            }
3902
            ReleaseCOMObjects(symbols);
3903
        }
3904

    
3905
        private void MoveSegmentBestLocation(string oid, double[] segmentRange, List<double[]> allRanges)
3906
        {
3907
            double minValue = Math.Min(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3908
            double maxValue = Math.Max(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3909

    
3910
            double maxX = 0, maxY = 0;
3911
            maxX = maxValue * 10;
3912
            maxY = minValue * 10;
3913

    
3914
            double move = minValue / 10d;
3915
            double textGap = minValue / 3d;
3916
            segmentRange = new double[] { segmentRange[0] - textGap, segmentRange[1] - textGap, segmentRange[2] + textGap, segmentRange[3] + textGap };
3917

    
3918

    
3919
            List<double[]> containRanges = new List<double[]>();
3920
            double[] findRange = new double[] {
3921
            segmentRange[0] - maxX, segmentRange[1] - maxY,
3922
            segmentRange[2] + maxX, segmentRange[3] + maxY};
3923

    
3924
            foreach (var range in allRanges)
3925
                if (SPPIDUtil.IsOverlap(findRange, range))
3926
                    containRanges.Add(range);
3927

    
3928
            double movePointX = 0, movePointY = 0, distance = double.MaxValue;
3929
            for (double x = 0; x < maxX; x = x + move)
3930
                for (double y = 0; y < maxY; y = y + move)
3931
                    for (int i = 0; i < 4; i++)
3932
                    {
3933
                        double tempX = 0d, tempY = 0d;
3934
                        switch (i)
3935
                        {
3936
                            case 0:
3937
                                tempX = x;
3938
                                tempY = y;
3939
                                break;
3940
                            case 1:
3941
                                tempX = -x;
3942
                                tempY = y;
3943
                                break;
3944
                            case 2:
3945
                                tempX = -x;
3946
                                tempY = -y;
3947
                                break;
3948
                            case 3:
3949
                                tempX = x;
3950
                                tempY = -y;
3951
                                break;
3952
                            default:
3953
                                break;
3954
                        }
3955

    
3956
                        bool result = true;
3957
                        double[] movedRange = new double[] { segmentRange[0] + tempX, segmentRange[1] + tempY, segmentRange[2] + tempX, segmentRange[3] + tempY };
3958
                        foreach (double[] range in containRanges)
3959
                        {
3960
                            if (SPPIDUtil.IsOverlap(range, movedRange))
3961
                            {
3962
                                result = false;
3963
                                break;
3964
                            }
3965
                        }
3966

    
3967
                        if (result)
3968
                        {
3969
                            //double tempDistance = Utils.CalcDistance(new double[] { 0, 0, 0 }, new double[] { tempX, tempY, 0 });
3970
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(0, 0, tempX, tempY);
3971
                            bool bChange = false;
3972
                            if (distance > tempDistance)
3973
                                bChange = true;
3974
                            else if (distance.Equals(tempDistance) && (movePointX.Equals(0d) || movePointY.Equals(0d)))
3975
                                bChange = true;
3976

    
3977
                            if (bChange)
3978
                            {
3979
                                distance = tempDistance;
3980
                                movePointX = tempX;
3981
                                movePointY = tempY;
3982
                            }
3983
                        }
3984
                    }
3985

    
3986
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3987
            if (dependency != null)
3988
            {
3989
                radApp.ActiveSelectSet.RemoveAll();
3990
                radApp.ActiveSelectSet.Add(dependency);
3991
                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3992
                transform.DefineByMove2d(movePointX, movePointY);
3993
                radApp.ActiveSelectSet.Transform(transform, true);
3994
                radApp.ActiveSelectSet.RemoveAll();
3995
            }
3996
        }
3997

    
3998
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3999
        {
4000
            LMConnector targetConnector = null;
4001
            Symbol targetSymbol = targetObj as Symbol;
4002
            Symbol connectedSymbol = connectedObj as Symbol;
4003
            Line targetLine = targetObj as Line;
4004
            Line connectedLine = connectedObj as Line;
4005
            if (targetSymbol != null && connectedSymbol != null)
4006
            {
4007
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4008
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4009

    
4010
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
4011
                {
4012
                    if (connector.get_ItemStatus() != "Active")
4013
                        continue;
4014

    
4015
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
4016
                    {
4017
                        targetConnector = connector;
4018
                        break;
4019
                    }
4020
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
4021
                    {
4022
                        targetConnector = connector;
4023
                        break;
4024
                    }
4025
                }
4026

    
4027
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
4028
                {
4029
                    if (connector.get_ItemStatus() != "Active")
4030
                        continue;
4031

    
4032
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
4033
                    {
4034
                        targetConnector = connector;
4035
                        break;
4036
                    }
4037
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
4038
                    {
4039
                        targetConnector = connector;
4040
                        break;
4041
                    }
4042
                }
4043

    
4044
                ReleaseCOMObjects(targetLMSymbol);
4045
                ReleaseCOMObjects(connectedLMSymbol);
4046
            }
4047
            else if (targetLine != null && connectedLine != null)
4048
            {
4049
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4050
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4051

    
4052
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
4053
                {
4054
                    foreach (LMRepresentation rep in targetModelItem.Representations)
4055
                    {
4056
                        if (targetConnector != null)
4057
                            break;
4058

    
4059
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4060
                        {
4061
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4062

    
4063
                            if (IsConnected(_LMConnector, connectedModelItem))
4064
                                targetConnector = _LMConnector;
4065
                            else
4066
                                ReleaseCOMObjects(_LMConnector);
4067
                        }
4068
                    }
4069

    
4070
                    ReleaseCOMObjects(targetModelItem);
4071
                }
4072
            }
4073
            else
4074
            {
4075
                LMSymbol connectedLMSymbol = null;
4076
                if (connectedSymbol != null)
4077
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4078
                else if (targetSymbol != null)
4079
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4080
                else
4081
                {
4082

    
4083
                }
4084
                LMModelItem targetModelItem = null;
4085
                if (targetLine != null)
4086
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4087
                else if (connectedLine != null)
4088
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4089
                else
4090
                {
4091

    
4092
                }
4093
                if (connectedLMSymbol != null && targetModelItem != null)
4094
                {
4095
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
4096
                    {
4097
                        if (connector.get_ItemStatus() != "Active")
4098
                            continue;
4099

    
4100
                        if (IsConnected(connector, targetModelItem))
4101
                        {
4102
                            targetConnector = connector;
4103
                            break;
4104
                        }
4105
                    }
4106

    
4107
                    if (targetConnector == null)
4108
                    {
4109
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
4110
                        {
4111
                            if (connector.get_ItemStatus() != "Active")
4112
                                continue;
4113

    
4114
                            if (IsConnected(connector, targetModelItem))
4115
                            {
4116
                                targetConnector = connector;
4117
                                break;
4118
                            }
4119
                        }
4120
                    }
4121
                }
4122

    
4123
            }
4124

    
4125
            return targetConnector;
4126
        }
4127

    
4128
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
4129
        {
4130
            double[] result = null;
4131
            Line targetLine = targetObj as Line;
4132
            Symbol targetSymbol = targetObj as Symbol;
4133
            Line connLine = connObj as Line;
4134
            Symbol connSymbol = connObj as Symbol;
4135
            location = SegmentLocation.None;
4136
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
4137
            {
4138
                result = GetConnectorVertices(targetConnector)[0];
4139
                if (targetSymbol != null && connSymbol != null)
4140
                {
4141
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
4142
                    result = new double[] { result[0], result[1] };
4143
                    if (slopeType == SlopeType.HORIZONTAL)
4144
                        location = SegmentLocation.Up;
4145
                    else if (slopeType == SlopeType.VERTICAL)
4146
                        location = SegmentLocation.Right;
4147
                }
4148
                else if (targetLine != null)
4149
                {
4150
                    result = new double[] { result[0], result[1] };
4151
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4152
                        location = SegmentLocation.Up;
4153
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
4154
                        location = SegmentLocation.Right;
4155
                }
4156
                else if (connLine != null)
4157
                {
4158
                    result = new double[] { result[0], result[1] };
4159
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
4160
                        location = SegmentLocation.Up;
4161
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
4162
                        location = SegmentLocation.Right;
4163
                }
4164
            }
4165
            else
4166
            {
4167
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
4168
                {
4169
                    Line line = connObj as Line;
4170
                    LMConnector connectedConnector = null;
4171
                    int connIndex = 0;
4172
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4173
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
4174

    
4175
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
4176

    
4177
                    ReleaseCOMObjects(modelItem);
4178
                    ReleaseCOMObjects(connectedConnector);
4179

    
4180
                    if (vertices.Count > 0)
4181
                    {
4182
                        if (connIndex == 1)
4183
                            result = vertices[0];
4184
                        else if (connIndex == 2)
4185
                            result = vertices[vertices.Count - 1];
4186

    
4187
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4188
                        {
4189
                            result = new double[] { result[0], result[1] };
4190
                            location = SegmentLocation.Up;
4191
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4192
                                location = location | SegmentLocation.Right;
4193
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4194
                                location = location | SegmentLocation.Left;
4195
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4196
                                location = location | SegmentLocation.Left;
4197
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4198
                                location = location | SegmentLocation.Right;
4199
                        }
4200
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
4201
                        {
4202
                            result = new double[] { result[0], result[1] };
4203
                            location = SegmentLocation.Right;
4204
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4205
                                location = location | SegmentLocation.Up;
4206
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4207
                                location = location | SegmentLocation.Down;
4208
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4209
                                location = location | SegmentLocation.Down;
4210
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4211
                                location = location | SegmentLocation.Up;
4212
                        }
4213

    
4214
                    }
4215
                }
4216
                else
4217
                {
4218
                    Log.Write("error in GetSegemtPoint");
4219
                }
4220
            }
4221

    
4222
            return result;
4223
        }
4224

    
4225
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
4226
        {
4227
            bool result = false;
4228

    
4229
            foreach (LMRepresentation rep in modelItem.Representations)
4230
            {
4231
                if (result)
4232
                    break;
4233

    
4234
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4235
                {
4236
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4237

    
4238
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4239
                        connector.ConnectItem1SymbolObject != null &&
4240
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4241
                    {
4242
                        result = true;
4243
                        ReleaseCOMObjects(_LMConnector);
4244
                        break;
4245
                    }
4246
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4247
                        connector.ConnectItem2SymbolObject != null &&
4248
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4249
                    {
4250
                        result = true;
4251
                        ReleaseCOMObjects(_LMConnector);
4252
                        break;
4253
                    }
4254
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4255
                        connector.ConnectItem1SymbolObject != null &&
4256
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4257
                    {
4258
                        result = true;
4259
                        ReleaseCOMObjects(_LMConnector);
4260
                        break;
4261
                    }
4262
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4263
                        connector.ConnectItem2SymbolObject != null &&
4264
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4265
                    {
4266
                        result = true;
4267
                        ReleaseCOMObjects(_LMConnector);
4268
                        break;
4269
                    }
4270

    
4271
                    ReleaseCOMObjects(_LMConnector);
4272
                }
4273
            }
4274

    
4275

    
4276
            return result;
4277
        }
4278

    
4279
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
4280
        {
4281
            foreach (LMRepresentation rep in modelItem.Representations)
4282
            {
4283
                if (connectedConnector != null)
4284
                    break;
4285

    
4286
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4287
                {
4288
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4289

    
4290
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4291
                        connector.ConnectItem1SymbolObject != null &&
4292
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4293
                    {
4294
                        connectedConnector = _LMConnector;
4295
                        connectorIndex = 1;
4296
                        break;
4297
                    }
4298
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4299
                        connector.ConnectItem2SymbolObject != null &&
4300
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4301
                    {
4302
                        connectedConnector = _LMConnector;
4303
                        connectorIndex = 2;
4304
                        break;
4305
                    }
4306
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4307
                        connector.ConnectItem1SymbolObject != null &&
4308
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4309
                    {
4310
                        connectedConnector = _LMConnector;
4311
                        connectorIndex = 1;
4312
                        break;
4313
                    }
4314
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4315
                        connector.ConnectItem2SymbolObject != null &&
4316
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4317
                    {
4318
                        connectedConnector = _LMConnector;
4319
                        connectorIndex = 2;
4320
                        break;
4321
                    }
4322

    
4323
                    if (connectedConnector == null)
4324
                        ReleaseCOMObjects(_LMConnector);
4325
                }
4326
            }
4327
        }
4328

    
4329
        /// <summary>
4330
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
4331
        /// </summary>
4332
        /// <param name="modelItemID1"></param>
4333
        /// <param name="modelItemID2"></param>
4334
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
4335
        {
4336
            try
4337
            {
4338
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
4339
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
4340
                List<double[]> vertices1 = null;
4341
                string graphicOID1 = string.Empty;
4342
                if (connector1 != null)
4343
                {
4344
                    vertices1 = GetConnectorVertices(connector1);
4345
                    graphicOID1 = connector1.get_GraphicOID();
4346
                }
4347
                _LMAItem item1 = modelItem1.AsLMAItem();
4348
                ReleaseCOMObjects(connector1);
4349
                connector1 = null;
4350

    
4351
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
4352
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
4353
                List<double[]> vertices2 = null;
4354
                string graphicOID2 = string.Empty;
4355
                if (connector2 != null)
4356
                {
4357
                    vertices2 = GetConnectorVertices(connector2);
4358
                    graphicOID2 = connector2.get_GraphicOID();
4359
                }
4360
                _LMAItem item2 = modelItem2.AsLMAItem();
4361
                ReleaseCOMObjects(connector2);
4362
                connector2 = null;
4363

    
4364

    
4365
                ISPClientData3.ISPItem ispItem1 = item1.ISPItem;
4366
                ISPClientData3.ISPItemType ispItemType1 = ispItem1.get_ItemType();
4367
                foreach (ISPClientData3.ISPAttribute attrib in ispItem1.get_Attributes())
4368
                {
4369
                    if (attrib.AttName == "PipeRunType")
4370
                    {
4371
                        string aa = attrib.Value;
4372
                    }
4373
                }
4374

    
4375

    
4376
                ISPClientData3.ISPItem ispItem2 = item2.ISPItem;
4377
                ISPClientData3.ISPItemType ispItemType2 = ispItem2.get_ItemType();
4378
                foreach (ISPClientData3.ISPAttribute attrib in ispItem2.get_Attributes())
4379
                {
4380
                    if (attrib.AttName == "PipeRunType")
4381
                    {
4382
                        string aa = attrib.Value;
4383
                    }
4384
                }
4385

    
4386

    
4387
                // item2가 item1으로 조인
4388
                _placement.PIDJoinRuns(ref item1, ref item2);
4389
                item1.Commit();
4390
                item2.Commit();
4391

    
4392
                string beforeID = string.Empty;
4393
                string afterID = string.Empty;
4394

    
4395
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
4396
                {
4397
                    beforeID = modelItem2.Id;
4398
                    afterID = modelItem1.Id;
4399
                    survivorId = afterID;
4400
                }
4401
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
4402
                {
4403
                    beforeID = modelItem1.Id;
4404
                    afterID = modelItem2.Id;
4405
                    survivorId = afterID;
4406
                }
4407
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
4408
                {
4409
                    int model1Cnt = GetConnectorCount(modelId1);
4410
                    int model2Cnt = GetConnectorCount(modelId2);
4411
                    if (model1Cnt == 0)
4412
                    {
4413
                        beforeID = modelItem1.Id;
4414
                        afterID = modelItem2.Id;
4415
                        survivorId = afterID;
4416
                    }
4417
                    else if (model2Cnt == 0)
4418
                    {
4419
                        beforeID = modelItem2.Id;
4420
                        afterID = modelItem1.Id;
4421
                        survivorId = afterID;
4422
                    }
4423
                    else
4424
                        survivorId = null;
4425
                }
4426
                else
4427
                {
4428
                    Log.Write("잘못된 경우");
4429
                    survivorId = null;
4430
                }
4431

    
4432
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
4433
                {
4434
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
4435
                    foreach (var line in lines)
4436
                        line.SPPID.ModelItemId = afterID;
4437
                }
4438

    
4439
                ReleaseCOMObjects(modelItem1);
4440
                ReleaseCOMObjects(item1);
4441
                ReleaseCOMObjects(modelItem2);
4442
                ReleaseCOMObjects(item2);
4443
            }
4444
            catch (Exception ex)
4445
            {
4446
                Log.Write("Join Error");
4447
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
4448
            }
4449
        }
4450
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
4451
        {
4452
            bool result = false;
4453
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
4454
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
4455
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
4456

    
4457
            foreach (var item in endBreaks)
4458
            {
4459
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
4460
                {
4461
                    result = true;
4462
                    break;
4463
                }
4464
            }
4465

    
4466
            return result;
4467
        }
4468
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
4469
        {
4470
            List<string> temp = new List<string>();
4471
            List<LMConnector> connectors = new List<LMConnector>();
4472
            foreach (LMConnector connector in symbol.Avoid1Connectors)
4473
            {
4474
                if (connector.get_ItemStatus() != "Active")
4475
                    continue;
4476

    
4477
                LMModelItem modelItem = connector.ModelItemObject;
4478
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4479
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4480
                    temp.Add(modelItem.Id);
4481

    
4482
                if (temp.Contains(modelItem.Id) &&
4483
                    connOtherSymbol != null &&
4484
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4485
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4486
                    temp.Remove(modelItem.Id);
4487

    
4488

    
4489
                if (temp.Contains(modelItem.Id))
4490
                    connectors.Add(connector);
4491
                ReleaseCOMObjects(connOtherSymbol);
4492
                connOtherSymbol = null;
4493
                ReleaseCOMObjects(modelItem);
4494
                modelItem = null;
4495
            }
4496

    
4497
            foreach (LMConnector connector in symbol.Avoid2Connectors)
4498
            {
4499
                if (connector.get_ItemStatus() != "Active")
4500
                    continue;
4501

    
4502
                LMModelItem modelItem = connector.ModelItemObject;
4503
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4504
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4505
                    temp.Add(modelItem.Id);
4506

    
4507
                if (temp.Contains(modelItem.Id) &&
4508
                    connOtherSymbol != null &&
4509
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4510
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4511
                    temp.Remove(modelItem.Id);
4512

    
4513
                if (temp.Contains(modelItem.Id))
4514
                    connectors.Add(connector);
4515
                ReleaseCOMObjects(connOtherSymbol);
4516
                connOtherSymbol = null;
4517
                ReleaseCOMObjects(modelItem);
4518
                modelItem = null;
4519
            }
4520

    
4521

    
4522
            List<string> result = new List<string>();
4523
            string originalName = GetSPPIDFileName(modelId);
4524
            foreach (var connector in connectors)
4525
            {
4526
                string fileName = GetSPPIDFileName(connector.ModelItemID);
4527
                if (originalName == fileName)
4528
                    result.Add(connector.ModelItemID);
4529
                else
4530
                {
4531
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
4532
                        result.Add(connector.ModelItemID);
4533
                    else
4534
                    {
4535
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
4536
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
4537
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
4538
                            result.Add(connector.ModelItemID);
4539
                    }
4540
                }
4541
            }
4542

    
4543
            foreach (var connector in connectors)
4544
                ReleaseCOMObjects(connector);
4545

    
4546
            return result;
4547

    
4548

    
4549
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
4550
            {
4551
                LMSymbol findResult = null;
4552
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
4553
                    findResult = connector.ConnectItem1SymbolObject;
4554
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
4555
                    findResult = connector.ConnectItem2SymbolObject;
4556

    
4557
                return findResult;
4558
            }
4559
        }
4560

    
4561
        /// <summary>
4562
        /// PipeRun의 좌표를 가져오는 메서드
4563
        /// </summary>
4564
        /// <param name="modelId"></param>
4565
        /// <returns></returns>
4566
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
4567
        {
4568
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
4569
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
4570

    
4571
            if (modelItem != null)
4572
            {
4573
                foreach (LMRepresentation rep in modelItem.Representations)
4574
                {
4575
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4576
                    {
4577
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4578
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
4579
                        {
4580
                            ReleaseCOMObjects(_LMConnector);
4581
                            _LMConnector = null;
4582
                            continue;
4583
                        }
4584
                        connectorVertices.Add(_LMConnector, new List<double[]>());
4585
                        dynamic OID = rep.get_GraphicOID().ToString();
4586
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4587
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4588
                        int verticesCount = lineStringGeometry.VertexCount;
4589
                        double[] vertices = null;
4590
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
4591
                        for (int i = 0; i < verticesCount; i++)
4592
                        {
4593
                            double x = 0;
4594
                            double y = 0;
4595
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4596
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
4597
                        }
4598
                    }
4599
                }
4600

    
4601
                ReleaseCOMObjects(modelItem);
4602
            }
4603

    
4604
            return connectorVertices;
4605
        }
4606

    
4607
        private List<double[]> GetConnectorVertices(LMConnector connector)
4608
        {
4609
            List<double[]> vertices = new List<double[]>();
4610
            if (connector != null)
4611
            {
4612
                dynamic OID = connector.get_GraphicOID().ToString();
4613
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4614
                if (drawingObject != null)
4615
                {
4616
                    Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4617
                    int verticesCount = lineStringGeometry.VertexCount;
4618
                    double[] value = null;
4619
                    lineStringGeometry.GetVertices(ref verticesCount, ref value);
4620
                    for (int i = 0; i < verticesCount; i++)
4621
                    {
4622
                        double x = 0;
4623
                        double y = 0;
4624
                        lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4625
                        vertices.Add(new double[] { x, y });
4626
                    }
4627
                }
4628
            }
4629
            return vertices;
4630
        }
4631

    
4632
        private double GetConnectorDistance(LMConnector connector)
4633
        {
4634
            double result = 0;
4635
            List<double[]> vertices = new List<double[]>();
4636
            if (connector != null)
4637
            {
4638
                dynamic OID = connector.get_GraphicOID().ToString();
4639
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4640
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4641
                int verticesCount = lineStringGeometry.VertexCount;
4642
                double[] value = null;
4643
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4644
                for (int i = 0; i < verticesCount; i++)
4645
                {
4646
                    double x = 0;
4647
                    double y = 0;
4648
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4649
                    vertices.Add(new double[] { x, y });
4650
                    if (vertices.Count > 1)
4651
                    {
4652
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
4653
                    }
4654
                }
4655
            }
4656
            return result;
4657
        }
4658
        private double[] GetConnectorRange(LMConnector connector)
4659
        {
4660
            double[] result = null;
4661
            List<double[]> vertices = new List<double[]>();
4662
            if (connector != null)
4663
            {
4664
                dynamic OID = connector.get_GraphicOID().ToString();
4665
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4666
                double minX = 0;
4667
                double minY = 0;
4668
                double maxX = 0;
4669
                double maxY = 0;
4670

    
4671
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
4672
                result = new double[] { minX, minY, maxX, maxY };
4673
            }
4674
            return result;
4675
        }
4676
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
4677
        {
4678
            List<double[]> vertices = null;
4679
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
4680
            if (drawingObject != null)
4681
            {
4682
                vertices = new List<double[]>();
4683
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4684
                int verticesCount = lineStringGeometry.VertexCount;
4685
                double[] value = null;
4686
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4687
                for (int i = 0; i < verticesCount; i++)
4688
                {
4689
                    double x = 0;
4690
                    double y = 0;
4691
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4692
                    vertices.Add(new double[] { x, y });
4693
                }
4694
            }
4695
            return vertices;
4696
        }
4697
        /// <summary>
4698
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
4699
        /// </summary>
4700
        /// <param name="connectorVertices"></param>
4701
        /// <param name="connX"></param>
4702
        /// <param name="connY"></param>
4703
        /// <returns></returns>
4704
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
4705
        {
4706
            double length = double.MaxValue;
4707
            LMConnector targetConnector = null;
4708
            foreach (var item in connectorVertices)
4709
            {
4710
                List<double[]> points = item.Value;
4711
                for (int i = 0; i < points.Count - 1; i++)
4712
                {
4713
                    double[] point1 = points[i];
4714
                    double[] point2 = points[i + 1];
4715
                    double x1 = Math.Min(point1[0], point2[0]);
4716
                    double y1 = Math.Min(point1[1], point2[1]);
4717
                    double x2 = Math.Max(point1[0], point2[0]);
4718
                    double y2 = Math.Max(point1[1], point2[1]);
4719

    
4720
                    if ((x1 <= connX && x2 >= connX) ||
4721
                        (y1 <= connY && y2 >= connY))
4722
                    {
4723
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
4724
                        if (length >= distance)
4725
                        {
4726
                            targetConnector = item.Key;
4727
                            length = distance;
4728
                        }
4729

    
4730
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
4731
                        if (length >= distance)
4732
                        {
4733
                            targetConnector = item.Key;
4734
                            length = distance;
4735
                        }
4736
                    }
4737
                }
4738
            }
4739

    
4740
            // 못찾았을때.
4741
            length = double.MaxValue;
4742
            if (targetConnector == null)
4743
            {
4744
                foreach (var item in connectorVertices)
4745
                {
4746
                    List<double[]> points = item.Value;
4747

    
4748
                    foreach (double[] point in points)
4749
                    {
4750
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
4751
                        if (length >= distance)
4752
                        {
4753
                            targetConnector = item.Key;
4754
                            length = distance;
4755
                        }
4756
                    }
4757
                }
4758
            }
4759

    
4760
            return targetConnector;
4761
        }
4762

    
4763
        private LMConnector FindTargetLMConnectorForBranch(Line currentLine, Line targetLine, ref double x, ref double y)
4764
        {
4765
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4766
            if (vertices.Count == 0)
4767
                return null;
4768

    
4769
            double length = double.MaxValue;
4770
            LMConnector targetConnector = null;
4771
            double[] resultPoint = null;
4772
            List<double[]> targetVertices = null;
4773

    
4774
            // Vertices 포인트에 제일 가까운곳
4775
            foreach (var item in vertices)
4776
            {
4777
                List<double[]> points = item.Value;
4778
                for (int i = 0; i < points.Count; i++)
4779
                {
4780
                    double[] point = points[i];
4781
                    double tempX = point[0];
4782
                    double tempY = point[1];
4783

    
4784
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4785
                    if (length >= distance)
4786
                    {
4787
                        targetConnector = item.Key;
4788
                        length = distance;
4789
                        resultPoint = point;
4790
                        targetVertices = item.Value;
4791
                    }
4792
                }
4793
            }
4794

    
4795
            // Vertices Cross에 제일 가까운곳
4796
            foreach (var item in vertices)
4797
            {
4798
                List<double[]> points = item.Value;
4799
                for (int i = 0; i < points.Count - 1; i++)
4800
                {
4801
                    double[] point1 = points[i];
4802
                    double[] point2 = points[i + 1];
4803

    
4804
                    double maxLineX = Math.Max(point1[0], point2[0]);
4805
                    double minLineX = Math.Min(point1[0], point2[0]);
4806
                    double maxLineY = Math.Max(point1[1], point2[1]);
4807
                    double minLineY = Math.Min(point1[1], point2[1]);
4808

    
4809
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4810

    
4811
                    double[] crossingPoint = SPPIDUtil.CalcLineCrossingPoint(currentLine.SPPID.START_X, currentLine.SPPID.START_Y, currentLine.SPPID.END_X, currentLine.SPPID.END_Y, point1[0], point1[1], point2[0], point2[1]);
4812
                    if (crossingPoint != null)
4813
                    {
4814
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4815
                        if (length >= distance)
4816
                        {
4817
                            if (slope == SlopeType.Slope &&
4818
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4819
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4820
                            {
4821
                                targetConnector = item.Key;
4822
                                length = distance;
4823
                                resultPoint = crossingPoint;
4824
                                targetVertices = item.Value;
4825
                            }
4826
                            else if (slope == SlopeType.HORIZONTAL &&
4827
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4828
                            {
4829
                                targetConnector = item.Key;
4830
                                length = distance;
4831
                                resultPoint = crossingPoint;
4832
                                targetVertices = item.Value;
4833
                            }
4834
                            else if (slope == SlopeType.VERTICAL &&
4835
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4836
                            {
4837
                                targetConnector = item.Key;
4838
                                length = distance;
4839
                                resultPoint = crossingPoint;
4840
                                targetVertices = item.Value;
4841
                            }
4842
                        }
4843
                    }
4844
                }
4845
            }
4846

    
4847
            foreach (var item in vertices)
4848
                if (item.Key != null && item.Key != targetConnector)
4849
                    ReleaseCOMObjects(item.Key);
4850

    
4851
            if (SPPIDUtil.IsBranchLine(currentLine, targetLine))
4852
            {
4853
                double tempResultX = resultPoint[0];
4854
                double tempResultY = resultPoint[1];
4855
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4856

    
4857
                GridSetting gridSetting = GridSetting.GetInstance();
4858
                for (int i = 0; i < targetVertices.Count; i++)
4859
                {
4860
                    double[] point = targetVertices[i];
4861
                    double tempX = targetVertices[i][0];
4862
                    double tempY = targetVertices[i][1];
4863
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4864
                    if (tempX == tempResultX && tempY == tempResultY)
4865
                    {
4866
                        if (i == 0)
4867
                        {
4868
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4869
                            bool containZeroLength = false;
4870
                            if (connSymbol != null)
4871
                            {
4872
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4873
                                {
4874
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4875
                                        containZeroLength = true;
4876
                                }
4877
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4878
                                {
4879
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4880
                                        containZeroLength = true;
4881
                                }
4882
                            }
4883

    
4884
                            if (connSymbol == null ||
4885
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4886
                                containZeroLength)
4887
                            {
4888
                                bool bCalcX = false;
4889
                                bool bCalcY = false;
4890
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4891
                                    bCalcX = true;
4892
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4893
                                    bCalcY = true;
4894
                                else
4895
                                {
4896
                                    bCalcX = true;
4897
                                    bCalcY = true;
4898
                                }
4899

    
4900
                                if (bCalcX)
4901
                                {
4902
                                    double nextX = targetVertices[i + 1][0];
4903
                                    double newX = 0;
4904
                                    if (nextX > tempX)
4905
                                    {
4906
                                        newX = tempX + gridSetting.Length;
4907
                                        if (newX > nextX)
4908
                                            newX = (point[0] + nextX) / 2;
4909
                                    }
4910
                                    else
4911
                                    {
4912
                                        newX = tempX - gridSetting.Length;
4913
                                        if (newX < nextX)
4914
                                            newX = (point[0] + nextX) / 2;
4915
                                    }
4916
                                    resultPoint = new double[] { newX, resultPoint[1] };
4917
                                }
4918

    
4919
                                if (bCalcY)
4920
                                {
4921
                                    double nextY = targetVertices[i + 1][1];
4922
                                    double newY = 0;
4923
                                    if (nextY > tempY)
4924
                                    {
4925
                                        newY = tempY + gridSetting.Length;
4926
                                        if (newY > nextY)
4927
                                            newY = (point[1] + nextY) / 2;
4928
                                    }
4929
                                    else
4930
                                    {
4931
                                        newY = tempY - gridSetting.Length;
4932
                                        if (newY < nextY)
4933
                                            newY = (point[1] + nextY) / 2;
4934
                                    }
4935
                                    resultPoint = new double[] { resultPoint[0], newY };
4936
                                }
4937
                            }
4938
                        }
4939
                        else if (i == targetVertices.Count - 1 && targetVertices.Count != 2)
4940
                        {
4941
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4942
                            bool containZeroLength = false;
4943
                            if (connSymbol != null)
4944
                            {
4945
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4946
                                {
4947
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4948
                                        containZeroLength = true;
4949
                                }
4950
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4951
                                {
4952
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4953
                                        containZeroLength = true;
4954
                                }
4955
                            }
4956

    
4957
                            if (connSymbol == null ||
4958
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4959
                                containZeroLength)
4960
                            {
4961
                                bool bCalcX = false;
4962
                                bool bCalcY = false;
4963
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4964
                                    bCalcX = true;
4965
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4966
                                    bCalcY = true;
4967
                                else
4968
                                {
4969
                                    bCalcX = true;
4970
                                    bCalcY = true;
4971
                                }
4972

    
4973
                                if (bCalcX)
4974
                                {
4975
                                    double nextX = targetVertices[i - 1][0];
4976
                                    double newX = 0;
4977
                                    if (nextX > tempX)
4978
                                    {
4979
                                        newX = tempX + gridSetting.Length;
4980
                                        if (newX > nextX)
4981
                                            newX = (point[0] + nextX) / 2;
4982
                                    }
4983
                                    else
4984
                                    {
4985
                                        newX = tempX - gridSetting.Length;
4986
                                        if (newX < nextX)
4987
                                            newX = (point[0] + nextX) / 2;
4988
                                    }
4989
                                    resultPoint = new double[] { newX, resultPoint[1] };
4990
                                }
4991

    
4992
                                if (bCalcY)
4993
                                {
4994
                                    double nextY = targetVertices[i - 1][1];
4995
                                    double newY = 0;
4996
                                    if (nextY > tempY)
4997
                                    {
4998
                                        newY = tempY + gridSetting.Length;
4999
                                        if (newY > nextY)
5000
                                            newY = (point[1] + nextY) / 2;
5001
                                    }
5002
                                    else
5003
                                    {
5004
                                        newY = tempY - gridSetting.Length;
5005
                                        if (newY < nextY)
5006
                                            newY = (point[1] + nextY) / 2;
5007
                                    }
5008
                                    resultPoint = new double[] { resultPoint[0], newY };
5009
                                }
5010
                            }
5011
                        }
5012
                        break;
5013
                    }
5014
                }
5015
            }
5016

    
5017
            x = resultPoint[0];
5018
            y = resultPoint[1];
5019

    
5020
            return targetConnector;
5021
        }
5022

    
5023
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
5024
        {
5025
            LMConnector result = null;
5026
            List<LMConnector> connectors = new List<LMConnector>();
5027
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5028

    
5029
            if (modelItem != null)
5030
            {
5031
                foreach (LMRepresentation rep in modelItem.Representations)
5032
                {
5033
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5034
                        connectors.Add(dataSource.GetConnector(rep.Id));
5035
                }
5036

    
5037
                ReleaseCOMObjects(modelItem);
5038
            }
5039

    
5040
            if (connectors.Count == 1)
5041
                result = connectors[0];
5042
            else
5043
                foreach (var item in connectors)
5044
                    ReleaseCOMObjects(item);
5045

    
5046
            return result;
5047
        }
5048

    
5049
        private LMConnector GetLMConnectorFirst(string modelItemID)
5050
        {
5051
            LMConnector result = null;
5052
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5053

    
5054
            if (modelItem != null)
5055
            {
5056
                foreach (LMRepresentation rep in modelItem.Representations)
5057
                {
5058
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" &&
5059
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
5060
                    {
5061
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5062
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
5063
                        {
5064
                            result = connector;
5065
                            break;
5066
                        }
5067
                        else
5068
                        {
5069
                            ReleaseCOMObjects(connector);
5070
                            connector = null;
5071
                        }
5072
                    }
5073
                }
5074
                ReleaseCOMObjects(modelItem);
5075
                modelItem = null;
5076
            }
5077

    
5078
            return result;
5079
        }
5080

    
5081
        private int GetConnectorCount(string modelItemID)
5082
        {
5083
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5084
            int result = 0;
5085
            if (modelItem != null)
5086
            {
5087
                foreach (LMRepresentation rep in modelItem.Representations)
5088
                {
5089
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5090
                        result++;
5091
                    ReleaseCOMObjects(rep);
5092
                }
5093
                ReleaseCOMObjects(modelItem);
5094
            }
5095

    
5096
            return result;
5097
        }
5098

    
5099
        public List<string> GetRepresentations(string modelItemID)
5100
        {
5101
            List<string> result = new List<string>(); ;
5102
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5103
            if (modelItem != null)
5104
            {
5105
                foreach (LMRepresentation rep in modelItem.Representations)
5106
                {
5107
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5108
                        result.Add(rep.Id);
5109
                }
5110
                ReleaseCOMObjects(modelItem);
5111
            }
5112

    
5113
            return result;
5114
        }
5115

    
5116
        private void LineNumberModeling(LineNumber lineNumber)
5117
        {
5118
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5119
            if (line != null)
5120
            {
5121
                double x = 0;
5122
                double y = 0;
5123
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
5124

    
5125
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5126
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
5127
                if (connectedLMConnector != null)
5128
                {
5129
                    Array points = new double[] { 0, x, y };
5130
                    lineNumber.SPPID.SPPID_X = x;
5131
                    lineNumber.SPPID.SPPID_Y = y;
5132
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
5133

    
5134
                    if (_LmLabelPresist != null)
5135
                    {
5136
                        _LmLabelPresist.Commit();
5137
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
5138
                        ReleaseCOMObjects(_LmLabelPresist);
5139
                    }
5140
                }
5141

    
5142
                foreach (var item in connectorVertices)
5143
                    ReleaseCOMObjects(item.Key);
5144
            }
5145
        }
5146
        private void LineNumberCorrectModeling(LineNumber lineNumber)
5147
        {
5148
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5149
            if (line == null || line.SPPID.Vertices == null)
5150
                return;
5151

    
5152
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
5153
            {
5154
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
5155
                if (removeLabel != null)
5156
                {
5157
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
5158
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
5159

    
5160
                    GridSetting gridSetting = GridSetting.GetInstance();
5161
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
5162

    
5163
                    double[] labelRange = null;
5164
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
5165
                    List<double[]> vertices = GetConnectorVertices(connector);
5166

    
5167
                    double[] resultStart = null;
5168
                    double[] resultEnd = null;
5169
                    double distance = double.MaxValue;
5170
                    for (int i = 0; i < vertices.Count - 1; i++)
5171
                    {
5172
                        double[] startPoint = vertices[i];
5173
                        double[] endPoint = vertices[i + 1];
5174
                        foreach (var item in line.SPPID.Vertices)
5175
                        {
5176
                            double[] lineStartPoint = item[0];
5177
                            double[] lineEndPoint = item[item.Count - 1];
5178

    
5179
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
5180
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
5181
                            if (tempDistance < distance)
5182
                            {
5183
                                distance = tempDistance;
5184
                                resultStart = startPoint;
5185
                                resultEnd = endPoint;
5186
                            }
5187
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
5188
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
5189
                            if (tempDistance < distance)
5190
                            {
5191
                                distance = tempDistance;
5192
                                resultStart = startPoint;
5193
                                resultEnd = endPoint;
5194
                            }
5195
                        }
5196
                    }
5197

    
5198
                    if (resultStart != null && resultEnd != null)
5199
                    {
5200
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
5201
                        double lineStartX = 0;
5202
                        double lineStartY = 0;
5203
                        double lineEndX = 0;
5204
                        double lineEndY = 0;
5205
                        double lineNumberX = 0;
5206
                        double lineNumberY = 0;
5207
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
5208
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
5209

    
5210
                        double lineX = (lineStartX + lineEndX) / 2;
5211
                        double lineY = (lineStartY + lineEndY) / 2;
5212
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
5213
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
5214

    
5215
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
5216
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
5217
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
5218
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
5219

    
5220
                        double offsetX = 0;
5221
                        double offsetY = 0;
5222
                        if (slope == SlopeType.HORIZONTAL)
5223
                        {
5224
                            // Line Number 아래
5225
                            if (lineY < lineNumberY)
5226
                            {
5227
                                offsetX = labelCenterX - SPPIDCenterX;
5228
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
5229
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5230
                            }
5231
                            // Line Number 위
5232
                            else
5233
                            {
5234
                                offsetX = labelCenterX - SPPIDCenterX;
5235
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
5236
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5237
                            }
5238
                        }
5239
                        else if (slope == SlopeType.VERTICAL)
5240
                        {
5241
                            // Line Number 오르쪽
5242
                            if (lineX < lineNumberX)
5243
                            {
5244
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
5245
                                offsetY = labelCenterY - SPPIDCenterY;
5246
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5247
                            }
5248
                            // Line Number 왼쪽
5249
                            else
5250
                            {
5251
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
5252
                                offsetY = labelCenterY - SPPIDCenterY;
5253
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5254
                            }
5255
                        }
5256

    
5257
                        if (offsetY != 0 || offsetY != 0)
5258
                        {
5259
                            if (connector.ConnectItem1SymbolObject != null &&
5260
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
5261
                            {
5262
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
5263

    
5264
                                double x1, y1, x2, y2, originX, originY;
5265
                                symbol.Range(out x1, out y1, out x2, out y2);
5266
                                symbol.GetOrigin(out originX, out originY);
5267
                                if (originX < lineNumber.SPPID.SPPID_X)
5268
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5269
                                else
5270
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5271
                            }
5272
                            else if (connector.ConnectItem2SymbolObject != null &&
5273
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
5274
                            {
5275
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
5276

    
5277
                                double x1, y1, x2, y2, originX, originY;
5278
                                symbol.Range(out x1, out y1, out x2, out y2);
5279
                                symbol.GetOrigin(out originX, out originY);
5280
                                if (originX < lineNumber.SPPID.SPPID_X)
5281
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5282
                                else
5283
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5284
                            }
5285

    
5286
                            radApp.ActiveSelectSet.RemoveAll();
5287
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
5288
                            if (dependency != null)
5289
                            {
5290
                                radApp.ActiveSelectSet.Add(dependency);
5291
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
5292
                                transform.DefineByMove2d(-offsetX, -offsetY);
5293
                                radApp.ActiveSelectSet.Transform(transform, true);
5294
                                radApp.ActiveSelectSet.RemoveAll();
5295
                            }
5296
                        }
5297

    
5298
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
5299
                        {
5300
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
5301
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
5302
                        }
5303
                    }
5304

    
5305

    
5306
                    ReleaseCOMObjects(connector);
5307
                    connector = null;
5308
                }
5309

    
5310
                ReleaseCOMObjects(removeLabel);
5311
                removeLabel = null;
5312
            }
5313
        }
5314
        /// <summary>
5315
        /// Flow Mark Modeling
5316
        /// </summary>
5317
        /// <param name="line"></param>
5318
        private void FlowMarkModeling(Line line)
5319
        {
5320
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
5321
            {
5322
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
5323
                if (connector != null)
5324
                {
5325
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
5326
                    List<double[]> vertices = GetConnectorVertices(connector);
5327
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
5328
                    double[] point = vertices[vertices.Count - 1];
5329
                    Array array = new double[] { 0, point[0], point[1] };
5330
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, null, null, LabeledItem: connector.AsLMRepresentation());
5331
                    if (_LMLabelPersist != null)
5332
                    {
5333
                        _LMLabelPersist.Commit();
5334
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
5335
                        ReleaseCOMObjects(_LMLabelPersist);
5336
                    }
5337
                }
5338
            }
5339
        }
5340

    
5341
        /// <summary>
5342
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
5343
        /// </summary>
5344
        /// <param name="lineNumber"></param>
5345
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
5346
        {
5347
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
5348
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
5349
            {
5350
                if (a.ATTRIBUTE == "Tag Seq No")
5351
                    return 1;
5352
                else if (b.ATTRIBUTE == "Tag Seq No")
5353
                    return -1;
5354

    
5355
                return 0;
5356
            }
5357

    
5358
            foreach (LineRun run in lineNumber.RUNS)
5359
            {
5360
                foreach (var item in run.RUNITEMS)
5361
                {
5362
                    if (item.GetType() == typeof(Line))
5363
                    {
5364
                        Line line = item as Line;
5365
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
5366
                        {
5367
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5368
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5369
                            {
5370
                                foreach (var attribute in lineNumber.ATTRIBUTES)
5371
                                {
5372
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
5373
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5374
                                    {
5375
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5376
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
5377
                                        {
5378
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5379
                                            if (_FluidSystemAttribute != null)
5380
                                            {
5381
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
5382
                                                if (dt.Rows.Count == 1)
5383
                                                {
5384
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5385
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5386
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5387
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5388
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5389

    
5390
                                                    if (_LMAAttribute != null)
5391
                                                    {
5392
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5393
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5394
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
5395
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5396
                                                    }
5397
                                                }
5398
                                                if (dt != null)
5399
                                                    dt.Dispose();
5400
                                            }
5401
                                        }
5402
                                        else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(attribute.VALUE) && _LMAAttribute != null)
5403
                                        {
5404
                                            DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", attribute.VALUE));
5405

    
5406
                                            if (rows.Length.Equals(1))
5407
                                            {
5408
                                                if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5409
                                                    attribute.VALUE = rows[0]["MetricStr"].ToString();
5410
                                                else
5411
                                                    attribute.VALUE = rows[0]["InchStr"].ToString();
5412

    
5413
                                                if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5414
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5415
                                                else if (_LMAAttribute.get_Value() != attribute.VALUE)
5416
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5417
                                            }
5418
                                        }
5419
                                        else if (_LMAAttribute != null)
5420
                                        {
5421
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5422
                                                _LMAAttribute.set_Value(attribute.VALUE);
5423
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
5424
                                                _LMAAttribute.set_Value(attribute.VALUE);
5425
                                        }
5426
                                    }
5427
                                }
5428
                                _LMModelItem.Commit();
5429
                            }
5430
                            if (_LMModelItem != null)
5431
                                ReleaseCOMObjects(_LMModelItem);
5432
                            endLine.Add(line.SPPID.ModelItemId);
5433
                        }
5434
                    }
5435
                }
5436
            }
5437
        }
5438

    
5439
        /// <summary>
5440
        /// Symbol Attribute 입력 메서드
5441
        /// </summary>
5442
        /// <param name="item"></param>
5443
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
5444
        {
5445
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
5446
            string sRep = null;
5447
            string sModelID = null;
5448
            if (targetItem.GetType() == typeof(Symbol))
5449
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
5450
            else if (targetItem.GetType() == typeof(Equipment))
5451
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
5452
            else if (targetItem.GetType() == typeof(Line))
5453
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
5454

    
5455
            if (!string.IsNullOrEmpty(sRep))
5456
            {
5457
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
5458
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
5459
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5460

    
5461
                foreach (var item in targetAttributes)
5462
                {
5463
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5464
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5465
                    {
5466
                        if (!mapping.IsText)
5467
                        {
5468
                            LMAAttribute _LMAAttribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5469
                            if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5470
                            {
5471
                                DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5472

    
5473
                                if (rows.Length.Equals(1))
5474
                                {
5475
                                    if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5476
                                        item.VALUE = rows[0]["MetricStr"].ToString();
5477
                                    else
5478
                                        item.VALUE = rows[0]["InchStr"].ToString();
5479

    
5480
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5481
                                        _LMAAttribute.set_Value(item.VALUE);
5482
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5483
                                        _LMAAttribute.set_Value(item.VALUE);
5484
                                }
5485
                            }
5486
                            else if (_LMAAttribute != null)
5487
                            {
5488
                                _LMAAttribute.set_Value(item.VALUE);
5489
                                // OPC 일경우 Attribute 저장
5490
                                if (targetItem.GetType() == typeof(Symbol))
5491
                                {
5492
                                    Symbol symbol = targetItem as Symbol;
5493
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
5494
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
5495
                                }
5496
                            }
5497
                        }
5498
                        else
5499
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
5500
                    }
5501
                }
5502
                _LMModelItem.Commit();
5503

    
5504
                ReleaseCOMObjects(_Attributes);
5505
                ReleaseCOMObjects(_LMModelItem);
5506
                ReleaseCOMObjects(_LMSymbol);
5507
            }
5508
            else if (!string.IsNullOrEmpty(sModelID))
5509
            {
5510
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
5511
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5512

    
5513
                foreach (var item in targetAttributes)
5514
                {
5515
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5516
                    if (mapping == null)
5517
                        continue;
5518

    
5519
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5520
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
5521
                    {
5522
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5523
                        if (_FluidSystemAttribute != null)
5524
                        {
5525
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
5526
                            if (dt.Rows.Count == 1)
5527
                            {
5528
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5529
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5530
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5531
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5532
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5533

    
5534
                                if (_LMAAttribute != null)
5535
                                {
5536
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5537
                                        _LMAAttribute.set_Value(item.VALUE);
5538
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5539
                                        _LMAAttribute.set_Value(item.VALUE);
5540
                                }
5541
                            }
5542
                            if (dt != null)
5543
                                dt.Dispose();
5544
                        }
5545
                    }
5546
                    else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5547
                    {
5548
                        DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5549

    
5550
                        if (rows.Length.Equals(1))
5551
                        {
5552
                            if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5553
                                item.VALUE = rows[0]["MetricStr"].ToString();
5554
                            else
5555
                                item.VALUE = rows[0]["InchStr"].ToString();
5556

    
5557
                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5558
                                _LMAAttribute.set_Value(item.VALUE);
5559
                            else if (_LMAAttribute.get_Value() != item.VALUE)
5560
                                _LMAAttribute.set_Value(item.VALUE);
5561
                        }
5562
                    }
5563
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5564
                    {
5565
                        if (!mapping.IsText)
5566
                        {
5567
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5568
                            if (_Attribute != null)
5569
                                _Attribute.set_Value(item.VALUE);
5570
                        }
5571
                    }
5572
                }
5573
                _LMModelItem.Commit();
5574

    
5575
                ReleaseCOMObjects(_Attributes);
5576
                ReleaseCOMObjects(_LMModelItem);
5577
            }
5578
        }
5579

    
5580
        /// <summary>
5581
        /// Input SpecBreak Attribute
5582
        /// </summary>
5583
        /// <param name="specBreak"></param>
5584
        private void InputSpecBreakAttribute(SpecBreak specBreak)
5585
        {
5586
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
5587
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
5588

    
5589
            if (upStreamObj != null &&
5590
                downStreamObj != null)
5591
            {
5592
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
5593

    
5594
                if (targetLMConnector != null)
5595
                {
5596
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
5597
                    {
5598
                        string symbolPath = _LMLabelPersist.get_FileName();
5599
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
5600
                        if (mapping != null)
5601
                        {
5602
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
5603
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5604
                            {
5605
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
5606
                                if (values.Length == 2)
5607
                                {
5608
                                    string upStreamValue = values[0];
5609
                                    string downStreamValue = values[1];
5610

    
5611
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
5612
                                }
5613
                            }
5614
                        }
5615
                    }
5616

    
5617
                    ReleaseCOMObjects(targetLMConnector);
5618
                }
5619
            }
5620

    
5621

    
5622
            #region 내부에서만 쓰는 메서드
5623
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
5624
            {
5625
                Symbol upStreamSymbol = _upStreamObj as Symbol;
5626
                Line upStreamLine = _upStreamObj as Line;
5627
                Symbol downStreamSymbol = _downStreamObj as Symbol;
5628
                Line downStreamLine = _downStreamObj as Line;
5629
                // 둘다 Line일 경우
5630
                if (upStreamLine != null && downStreamLine != null)
5631
                {
5632
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5633
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5634
                }
5635
                // 둘다 Symbol일 경우
5636
                else if (upStreamSymbol != null && downStreamSymbol != null)
5637
                {
5638
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
5639
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5640
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5641

    
5642
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5643
                    {
5644
                        if (connector.get_ItemStatus() != "Active")
5645
                            continue;
5646

    
5647
                        if (connector.Id != zeroLenthConnector.Id)
5648
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5649
                    }
5650

    
5651
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5652
                    {
5653
                        if (connector.get_ItemStatus() != "Active")
5654
                            continue;
5655

    
5656
                        if (connector.Id != zeroLenthConnector.Id)
5657
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5658
                    }
5659

    
5660
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5661
                    {
5662
                        if (connector.get_ItemStatus() != "Active")
5663
                            continue;
5664

    
5665
                        if (connector.Id != zeroLenthConnector.Id)
5666
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5667
                    }
5668

    
5669
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5670
                    {
5671
                        if (connector.get_ItemStatus() != "Active")
5672
                            continue;
5673

    
5674
                        if (connector.Id != zeroLenthConnector.Id)
5675
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5676
                    }
5677

    
5678
                    ReleaseCOMObjects(zeroLenthConnector);
5679
                    ReleaseCOMObjects(upStreamLMSymbol);
5680
                    ReleaseCOMObjects(downStreamLMSymbol);
5681
                }
5682
                else if (upStreamSymbol != null && downStreamLine != null)
5683
                {
5684
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
5685
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5686
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5687

    
5688
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5689
                    {
5690
                        if (connector.get_ItemStatus() != "Active")
5691
                            continue;
5692

    
5693
                        if (connector.Id == zeroLenthConnector.Id)
5694
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5695
                    }
5696

    
5697
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5698
                    {
5699
                        if (connector.get_ItemStatus() != "Active")
5700
                            continue;
5701

    
5702
                        if (connector.Id == zeroLenthConnector.Id)
5703
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5704
                    }
5705

    
5706
                    ReleaseCOMObjects(zeroLenthConnector);
5707
                    ReleaseCOMObjects(upStreamLMSymbol);
5708
                }
5709
                else if (upStreamLine != null && downStreamSymbol != null)
5710
                {
5711
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
5712
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5713
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5714

    
5715
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5716
                    {
5717
                        if (connector.get_ItemStatus() != "Active")
5718
                            continue;
5719

    
5720
                        if (connector.Id == zeroLenthConnector.Id)
5721
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5722
                    }
5723

    
5724
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5725
                    {
5726
                        if (connector.get_ItemStatus() != "Active")
5727
                            continue;
5728

    
5729
                        if (connector.Id == zeroLenthConnector.Id)
5730
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5731
                    }
5732

    
5733
                    ReleaseCOMObjects(zeroLenthConnector);
5734
                    ReleaseCOMObjects(downStreamLMSymbol);
5735
                }
5736
            }
5737

    
5738
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
5739
            {
5740
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5741
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5742
                {
5743
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5744
                    if (_LMAAttribute != null)
5745
                    {
5746
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5747
                            _LMAAttribute.set_Value(value);
5748
                        else if (_LMAAttribute.get_Value() != value)
5749
                            _LMAAttribute.set_Value(value);
5750
                    }
5751

    
5752
                    _LMModelItem.Commit();
5753
                }
5754
                if (_LMModelItem != null)
5755
                    ReleaseCOMObjects(_LMModelItem);
5756
            }
5757

    
5758
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
5759
            {
5760
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
5761
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5762
                {
5763
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5764
                    if (_LMAAttribute != null)
5765
                    {
5766
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5767
                            _LMAAttribute.set_Value(value);
5768
                        else if (_LMAAttribute.get_Value() != value)
5769
                            _LMAAttribute.set_Value(value);
5770
                    }
5771

    
5772
                    _LMModelItem.Commit();
5773
                }
5774
                if (_LMModelItem != null)
5775
                    ReleaseCOMObjects(_LMModelItem);
5776
            }
5777
            #endregion
5778
        }
5779

    
5780
        private void InputEndBreakAttribute(EndBreak endBreak)
5781
        {
5782
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5783
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5784

    
5785
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
5786
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
5787
            {
5788
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
5789
                if (labelPersist != null)
5790
                {
5791
                    LMRepresentation representation = labelPersist.RepresentationObject;
5792
                    if (representation != null)
5793
                    {
5794
                        LMConnector connector = dataSource.GetConnector(representation.Id);
5795
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
5796
                        string modelItemID = connector.ModelItemID;
5797
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
5798
                        {
5799
                            List<string> modelItemIDs = new List<string>();
5800
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5801
                            {
5802
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
5803
                                foreach (LMConnector item in symbol.Connect1Connectors)
5804
                                {
5805
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5806
                                        modelItemIDs.Add(item.ModelItemID);
5807
                                    ReleaseCOMObjects(item);
5808
                                }
5809
                                foreach (LMConnector item in symbol.Connect2Connectors)
5810
                                {
5811
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5812
                                        modelItemIDs.Add(item.ModelItemID);
5813
                                    ReleaseCOMObjects(item);
5814
                                }
5815
                                ReleaseCOMObjects(symbol);
5816
                                symbol = null;
5817
                            }
5818
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5819
                            {
5820
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
5821
                                foreach (LMConnector item in symbol.Connect1Connectors)
5822
                                {
5823
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5824
                                        modelItemIDs.Add(item.ModelItemID);
5825
                                    ReleaseCOMObjects(item);
5826
                                }
5827
                                foreach (LMConnector item in symbol.Connect2Connectors)
5828
                                {
5829
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5830
                                        modelItemIDs.Add(item.ModelItemID);
5831
                                    ReleaseCOMObjects(item);
5832
                                }
5833
                                ReleaseCOMObjects(symbol);
5834
                                symbol = null;
5835
                            }
5836

    
5837
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5838
                            if (modelItemIDs.Count == 1)
5839
                            {
5840
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5841
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5842
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5843
                                {
5844
                                    bool result = false;
5845
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5846
                                    {
5847
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5848
                                            result = true;
5849
                                        ReleaseCOMObjects(loop);
5850
                                    }
5851

    
5852
                                    if (result)
5853
                                    {
5854
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5855
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5856
                                        //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5857
                                        //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5858
                                        ZeroLengthModelItem.Commit();
5859
                                    }
5860
                                    else
5861
                                    {
5862
                                        List<string> loopModelItems = new List<string>();
5863
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5864
                                        {
5865
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5866
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5867
                                            {
5868
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5869
                                                    loopModelItems.Add(loop.ModelItemID);
5870
                                                ReleaseCOMObjects(loop);
5871
                                            }
5872
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5873
                                            {
5874
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5875
                                                    loopModelItems.Add(loop.ModelItemID);
5876
                                                ReleaseCOMObjects(loop);
5877
                                            }
5878
                                            ReleaseCOMObjects(_symbol);
5879
                                            _symbol = null;
5880
                                        }
5881
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5882
                                        {
5883
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5884
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5885
                                            {
5886
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5887
                                                    loopModelItems.Add(loop.ModelItemID);
5888
                                                ReleaseCOMObjects(loop);
5889
                                            }
5890
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5891
                                            {
5892
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5893
                                                    loopModelItems.Add(loop.ModelItemID);
5894
                                                ReleaseCOMObjects(loop);
5895
                                            }
5896
                                            ReleaseCOMObjects(_symbol);
5897
                                            _symbol = null;
5898
                                        }
5899

    
5900
                                        loopModelItems = loopModelItems.Distinct().ToList();
5901
                                        if (loopModelItems.Count == 1)
5902
                                        {
5903
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5904
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5905
                                            //object value2 = loopModelItem.Attributes["SubUnitNumber"].get_Value();
5906
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5907
                                            //modelItem.Attributes["SubUnitNumber"].set_Value(value2);
5908
                                            modelItem.Commit();
5909
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5910
                                            //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5911
                                            ZeroLengthModelItem.Commit();
5912

    
5913
                                            ReleaseCOMObjects(loopModelItem);
5914
                                            loopModelItem = null;
5915
                                        }
5916
                                    }
5917
                                }
5918
                                else
5919
                                {
5920
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5921
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5922
                                    //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5923
                                    //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5924
                                    ZeroLengthModelItem.Commit();
5925
                                }
5926
                                ReleaseCOMObjects(modelItem);
5927
                                modelItem = null;
5928
                                ReleaseCOMObjects(onlyOne);
5929
                                onlyOne = null;
5930
                            }
5931
                        }
5932
                        ReleaseCOMObjects(connector);
5933
                        connector = null;
5934
                        ReleaseCOMObjects(ZeroLengthModelItem);
5935
                        ZeroLengthModelItem = null;
5936
                    }
5937
                    ReleaseCOMObjects(representation);
5938
                    representation = null;
5939
                }
5940
                ReleaseCOMObjects(labelPersist);
5941
                labelPersist = null;
5942
            }
5943
        }
5944

    
5945
        /// <summary>
5946
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5947
        /// </summary>
5948
        /// <param name="text"></param>
5949
        private void NormalTextModeling(Text text)
5950
        {
5951
            LMSymbol _LMSymbol = null;
5952

    
5953
            LMItemNote _LMItemNote = null;
5954
            LMAAttribute _LMAAttribute = null;
5955

    
5956
            double x = 0;
5957
            double y = 0;
5958
            double angle = text.ANGLE;
5959
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5960

    
5961
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5962
            text.SPPID.SPPID_X = x;
5963
            text.SPPID.SPPID_Y = y;
5964

    
5965
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5966
            if (_LMSymbol != null)
5967
            {
5968
                _LMSymbol.Commit();
5969
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5970
                if (_LMItemNote != null)
5971
                {
5972
                    _LMItemNote.Commit();
5973
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5974
                    if (_LMAAttribute != null)
5975
                    {
5976
                        _LMAAttribute.set_Value(text.VALUE);
5977
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5978
                        _LMItemNote.Commit();
5979

    
5980

    
5981
                        double[] range = null;
5982
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5983
                        {
5984
                            double[] temp = null;
5985
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5986
                            if (temp != null)
5987
                            {
5988
                                if (range == null)
5989
                                    range = temp;
5990
                                else
5991
                                {
5992
                                    range = new double[] {
5993
                                            Math.Min(range[0], temp[0]),
5994
                                            Math.Min(range[1], temp[1]),
5995
                                            Math.Max(range[2], temp[2]),
5996
                                            Math.Max(range[3], temp[3])
5997
                                        };
5998
                                }
5999
                            }
6000
                        }
6001
                        text.SPPID.Range = range;
6002

    
6003
                        if (_LMAAttribute != null)
6004
                            ReleaseCOMObjects(_LMAAttribute);
6005
                        if (_LMItemNote != null)
6006
                            ReleaseCOMObjects(_LMItemNote);
6007
                    }
6008

    
6009
                    TextCorrectModeling(text);
6010
                }
6011
            }
6012
            if (_LMSymbol != null)
6013
                ReleaseCOMObjects(_LMSymbol);
6014
        }
6015

    
6016
        private void DefaultTextModeling(string value, double x, double y)
6017
        {
6018
            LMSymbol _LMSymbol = null;
6019

    
6020
            LMItemNote _LMItemNote = null;
6021
            LMAAttribute _LMAAttribute = null;
6022

    
6023
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
6024
            if (_LMSymbol != null)
6025
            {
6026
                _LMSymbol.Commit();
6027
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6028
                if (_LMItemNote != null)
6029
                {
6030
                    _LMItemNote.Commit();
6031
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6032
                    if (_LMAAttribute != null)
6033
                    {
6034
                        _LMAAttribute.set_Value(value);
6035
                        _LMItemNote.Commit();
6036

    
6037
                        if (_LMAAttribute != null)
6038
                            ReleaseCOMObjects(_LMAAttribute);
6039
                        if (_LMItemNote != null)
6040
                            ReleaseCOMObjects(_LMItemNote);
6041
                    }
6042
                }
6043
            }
6044
            if (_LMSymbol != null)
6045
                ReleaseCOMObjects(_LMSymbol);
6046
        }
6047

    
6048
        private void AssociationTextModeling(Text text)
6049
        {
6050
            LMSymbol _LMSymbol = null;
6051
            LMConnector connectedLMConnector = null;
6052
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6053
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
6054
            {
6055
                Symbol symbol = owner as Symbol;
6056
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6057
                if (_LMSymbol != null)
6058
                {
6059
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6060
                    {
6061
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6062
                        {
6063
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6064

    
6065
                            if (mapping != null)
6066
                            {
6067
                                double x = 0;
6068
                                double y = 0;
6069

    
6070
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6071
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6072
                                Array array = new double[] { 0, x, y };
6073
                                text.SPPID.SPPID_X = x;
6074
                                text.SPPID.SPPID_Y = y;
6075
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6076
                                if (_LMLabelPersist != null)
6077
                                {
6078
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6079
                                    _LMLabelPersist.Commit();
6080
                                    ReleaseCOMObjects(_LMLabelPersist);
6081
                                }
6082
                            }
6083
                        }
6084
                    }
6085
                }
6086
            }
6087
            else if (owner != null && owner.GetType() == typeof(Line))
6088
            {
6089
                Line line = owner as Line;
6090
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
6091
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
6092

    
6093
                if (connectedLMConnector != null)
6094
                {
6095
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6096
                    {
6097
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6098
                        {
6099
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6100

    
6101
                            if (mapping != null)
6102
                            {
6103
                                double x = 0;
6104
                                double y = 0;
6105
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6106
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6107
                                Array array = new double[] { 0, x, y };
6108

    
6109
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6110
                                if (_LMLabelPersist != null)
6111
                                {
6112
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6113
                                    _LMLabelPersist.Commit();
6114

    
6115
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
6116
                                    if (dependency != null)
6117
                                    {
6118
                                        radApp.ActiveSelectSet.RemoveAll();
6119
                                        radApp.ActiveSelectSet.Add(dependency);
6120
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
6121
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
6122
                                        radApp.ActiveSelectSet.Transform(transform, true);
6123
                                        radApp.ActiveSelectSet.RemoveAll();
6124
                                    }
6125

    
6126
                                    ReleaseCOMObjects(_LMLabelPersist);
6127
                                }
6128
                            }
6129
                        }
6130
                    }
6131
                }
6132
            }
6133
            if (_LMSymbol != null)
6134
                ReleaseCOMObjects(_LMSymbol);
6135
        }
6136

    
6137
        private void TextCorrectModeling(Text text)
6138
        {
6139
            if (text.SPPID.Range == null)
6140
                return;
6141

    
6142
            bool needRemodeling = false;
6143
            bool loop = true;
6144
            GridSetting gridSetting = GridSetting.GetInstance();
6145
            while (loop)
6146
            {
6147
                loop = false;
6148
                foreach (var overlapText in document.TEXTINFOS)
6149
                {
6150
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
6151
                        continue;
6152

    
6153
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
6154
                    {
6155
                        double percentX = 0;
6156
                        double percentY = 0;
6157
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
6158
                        {
6159
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
6160
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
6161
                        }
6162
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
6163
                        {
6164
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
6165
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
6166
                        }
6167

    
6168
                        double tempX = 0;
6169
                        double tempY = 0;
6170
                        bool overlapX = false;
6171
                        bool overlapY = false;
6172
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6173
                        if (percentX >= percentY)
6174
                        {
6175
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6176
                            double move = gridSetting.Length * count;
6177
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
6178
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
6179
                            needRemodeling = true;
6180
                            loop = true;
6181
                        }
6182
                        else
6183
                        {
6184
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6185
                            double move = gridSetting.Length * count;
6186
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
6187
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
6188
                            needRemodeling = true;
6189
                            loop = true;
6190
                        }
6191
                    }
6192
                }
6193
            }
6194

    
6195

    
6196
            if (needRemodeling)
6197
            {
6198
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
6199
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6200
                text.SPPID.RepresentationId = null;
6201

    
6202
                LMItemNote _LMItemNote = null;
6203
                LMAAttribute _LMAAttribute = null;
6204
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
6205
                if (_LMSymbol != null)
6206
                {
6207
                    _LMSymbol.Commit();
6208
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6209
                    if (_LMItemNote != null)
6210
                    {
6211
                        _LMItemNote.Commit();
6212
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6213
                        if (_LMAAttribute != null)
6214
                        {
6215
                            _LMAAttribute.set_Value(text.VALUE);
6216
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6217
                            _LMItemNote.Commit();
6218

    
6219
                            ReleaseCOMObjects(_LMAAttribute);
6220
                            ReleaseCOMObjects(_LMItemNote);
6221
                        }
6222
                    }
6223
                }
6224

    
6225
                ReleaseCOMObjects(symbol);
6226
                symbol = null;
6227
                ReleaseCOMObjects(_LMItemNote);
6228
                _LMItemNote = null;
6229
                ReleaseCOMObjects(_LMAAttribute);
6230
                _LMAAttribute = null;
6231
                ReleaseCOMObjects(_LMSymbol);
6232
                _LMSymbol = null;
6233
            }
6234
        }
6235

    
6236
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
6237
        {
6238
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
6239
            {
6240
                List<Text> allTexts = new List<Text>();
6241
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6242
                LMRepresentation representation = targetLabel.RepresentationObject;
6243
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
6244
                if (targetLabel.RepresentationObject != null && symbol != null)
6245
                {
6246
                    double[] symbolRange = null;
6247
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
6248
                    if (symbolRange != null)
6249
                    {
6250
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
6251
                        {
6252
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
6253
                            if (findText != null)
6254
                            {
6255
                                double[] range = null;
6256
                                GetSPPIDSymbolRange(labelPersist, ref range);
6257
                                findText.SPPID.Range = range;
6258
                                allTexts.Add(findText);
6259
                            }
6260

    
6261
                            ReleaseCOMObjects(labelPersist);
6262
                        }
6263

    
6264
                        if (allTexts.Count > 0)
6265
                        {
6266
                            #region Sort Text By Y
6267
                            allTexts.Sort(SortTextByY);
6268
                            int SortTextByY(Text a, Text b)
6269
                            {
6270
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
6271
                            }
6272
                            #endregion
6273

    
6274
                            #region 정렬하기전 방향
6275
                            List<Text> left = new List<Text>();
6276
                            List<Text> down = new List<Text>();
6277
                            List<Text> right = new List<Text>();
6278
                            List<Text> up = new List<Text>();
6279
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
6280
                            foreach (var loopText in allTexts)
6281
                            {
6282
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
6283
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
6284
                                double originX = 0;
6285
                                double originY = 0;
6286
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6287
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6288

    
6289
                                if (angle < 45)
6290
                                {
6291
                                    // Text 오른쪽
6292
                                    if (textCenterX > originX)
6293
                                        right.Add(loopText);
6294
                                    // Text 왼쪽
6295
                                    else
6296
                                        left.Add(loopText);
6297
                                }
6298
                                else
6299
                                {
6300
                                    // Text 아래쪽
6301
                                    if (textCenterY > originY)
6302
                                        down.Add(loopText);
6303
                                    // Text 위쪽
6304
                                    else
6305
                                        up.Add(loopText);
6306
                                }
6307
                            }
6308

    
6309
                            #endregion
6310

    
6311
                            foreach (var texts in sortTexts)
6312
                            {
6313
                                if (texts.Count == 0)
6314
                                    continue;
6315

    
6316
                                #region 첫번째 Text로 기준 맞춤
6317
                                for (int i = 0; i < texts.Count; i++)
6318
                                {
6319
                                    if (i != 0)
6320
                                    {
6321
                                        Text currentText = texts[i];
6322
                                        Text prevText = texts[i - 1];
6323
                                        double minY = prevText.SPPID.Range[1];
6324
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
6325
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
6326
                                        double _gapX = centerX - centerPrevX;
6327
                                        double _gapY = currentText.SPPID.Range[3] - minY;
6328
                                        MoveText(currentText, _gapX, _gapY);
6329
                                    }
6330
                                }
6331
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
6332
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
6333
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
6334
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
6335
                                rangeMinX.Sort();
6336
                                rangeMinY.Sort();
6337
                                rangeMaxX.Sort();
6338
                                rangeMaxY.Sort();
6339
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
6340
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
6341
                                #endregion
6342
                                #region 정렬
6343
                                Text correctBySymbol = texts[0];
6344
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
6345
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
6346
                                double originX = 0;
6347
                                double originY = 0;
6348
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6349
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6350
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
6351
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
6352

    
6353
                                double gapX = 0;
6354
                                double gapY = 0;
6355
                                if (angle < 45)
6356
                                {
6357
                                    // Text 오른쪽
6358
                                    if (textCenterX > originX)
6359
                                    {
6360
                                        gapX = rangeMinX[0] - symbolRange[2];
6361
                                        gapY = allTextCenterY - symbolCenterY;
6362
                                    }
6363
                                    // Text 왼쪽
6364
                                    else
6365
                                    {
6366
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
6367
                                        gapY = allTextCenterY - symbolCenterY;
6368
                                    }
6369
                                }
6370
                                else
6371
                                {
6372
                                    // Text 아래쪽
6373
                                    if (textCenterY > originY)
6374
                                    {
6375
                                        gapX = allTextCenterX - symbolCenterX;
6376
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
6377
                                    }
6378
                                    // Text 위쪽
6379
                                    else
6380
                                    {
6381
                                        gapX = allTextCenterX - symbolCenterX;
6382
                                        gapY = rangeMinY[0] - symbolRange[3];
6383
                                    }
6384
                                }
6385

    
6386
                                foreach (var item in texts)
6387
                                {
6388
                                    MoveText(item, gapX, gapY);
6389
                                    RemodelingAssociationText(item);
6390
                                }
6391
                                #endregion
6392
                            }
6393
                        }
6394
                    }
6395
                }
6396

    
6397
                void MoveText(Text moveText, double x, double y)
6398
                {
6399
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
6400
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
6401
                    moveText.SPPID.Range = new double[] {
6402
                        moveText.SPPID.Range[0] - x,
6403
                        moveText.SPPID.Range[1]- y,
6404
                        moveText.SPPID.Range[2]- x,
6405
                        moveText.SPPID.Range[3]- y
6406
                    };
6407
                }
6408

    
6409
                endTexts.AddRange(allTexts);
6410

    
6411
                ReleaseCOMObjects(targetLabel);
6412
                targetLabel = null;
6413
                ReleaseCOMObjects(representation);
6414
                representation = null;
6415
            }
6416
        }
6417

    
6418
        private void RemodelingAssociationText(Text text)
6419
        {
6420
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6421
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
6422
            removeLabel.Commit();
6423
            ReleaseCOMObjects(removeLabel);
6424
            removeLabel = null;
6425

    
6426
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6427
            if (owner != null && owner.GetType() == typeof(Symbol))
6428
            {
6429
                Symbol symbol = owner as Symbol;
6430
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6431
                if (_LMSymbol != null)
6432
                {
6433
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
6434
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6435
                    {
6436
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6437

    
6438
                        if (mapping != null)
6439
                        {
6440
                            double x = 0;
6441
                            double y = 0;
6442

    
6443
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
6444
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6445
                            if (_LMLabelPersist != null)
6446
                            {
6447
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6448
                                _LMLabelPersist.Commit();
6449
                            }
6450
                            ReleaseCOMObjects(_LMLabelPersist);
6451
                            _LMLabelPersist = null;
6452
                        }
6453
                    }
6454
                }
6455
                ReleaseCOMObjects(_LMSymbol);
6456
                _LMSymbol = null;
6457
            }
6458
        }
6459

    
6460
        /// <summary>
6461
        /// Note Modeling
6462
        /// </summary>
6463
        /// <param name="note"></param>
6464
        private void NoteModeling(Note note, List<Note> correctList)
6465
        {
6466
            LMSymbol _LMSymbol = null;
6467
            LMItemNote _LMItemNote = null;
6468
            LMAAttribute _LMAAttribute = null;
6469

    
6470
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
6471
            {
6472
                double x = 0;
6473
                double y = 0;
6474

    
6475
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
6476
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6477
                note.SPPID.SPPID_X = x;
6478
                note.SPPID.SPPID_Y = y;
6479

    
6480
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
6481
                if (_LMSymbol != null)
6482
                {
6483
                    _LMSymbol.Commit();
6484
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6485
                    if (_LMItemNote != null)
6486
                    {
6487
                        _LMItemNote.Commit();
6488
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6489
                        if (_LMAAttribute != null)
6490
                        {
6491
                            _LMAAttribute.set_Value(note.VALUE);
6492
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6493

    
6494
                            double[] range = null;
6495
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6496
                            {
6497
                                double[] temp = null;
6498
                                GetSPPIDSymbolRange(labelPersist, ref temp);
6499
                                if (temp != null)
6500
                                {
6501
                                    if (range == null)
6502
                                        range = temp;
6503
                                    else
6504
                                    {
6505
                                        range = new double[] {
6506
                                            Math.Min(range[0], temp[0]),
6507
                                            Math.Min(range[1], temp[1]),
6508
                                            Math.Max(range[2], temp[2]),
6509
                                            Math.Max(range[3], temp[3])
6510
                                        };
6511
                                    }
6512
                                }
6513
                            }
6514
                            if (range != null)
6515
                                correctList.Add(note);
6516
                            note.SPPID.Range = range;
6517

    
6518

    
6519
                            _LMItemNote.Commit();
6520
                        }
6521
                    }
6522
                }
6523
            }
6524

    
6525
            if (_LMAAttribute != null)
6526
                ReleaseCOMObjects(_LMAAttribute);
6527
            if (_LMItemNote != null)
6528
                ReleaseCOMObjects(_LMItemNote);
6529
            if (_LMSymbol != null)
6530
                ReleaseCOMObjects(_LMSymbol);
6531
        }
6532

    
6533
        private void NoteCorrectModeling(Note note, List<Note> endList)
6534
        {
6535
            bool needRemodeling = false;
6536
            bool loop = true;
6537
            GridSetting gridSetting = GridSetting.GetInstance();
6538
            while (loop)
6539
            {
6540
                loop = false;
6541
                foreach (var overlap in endList)
6542
                {
6543
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
6544
                    {
6545
                        double tempX = 0;
6546
                        double tempY = 0;
6547
                        bool overlapX = false;
6548
                        bool overlapY = false;
6549
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6550
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
6551
                        if (overlapY && angle >= 45)
6552
                        {
6553
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6554
                            double move = gridSetting.Length * count;
6555
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
6556
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
6557
                            needRemodeling = true;
6558
                            loop = true;
6559
                        }
6560
                        if (overlapX && angle <= 45)
6561
                        {
6562
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6563
                            double move = gridSetting.Length * count;
6564
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
6565
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
6566
                            needRemodeling = true;
6567
                            loop = true;
6568
                        }
6569
                    }
6570
                }
6571
            }
6572

    
6573

    
6574
            if (needRemodeling)
6575
            {
6576
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
6577
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6578
                note.SPPID.RepresentationId = null;
6579

    
6580
                LMItemNote _LMItemNote = null;
6581
                LMAAttribute _LMAAttribute = null;
6582
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
6583
                if (_LMSymbol != null)
6584
                {
6585
                    _LMSymbol.Commit();
6586
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6587
                    if (_LMItemNote != null)
6588
                    {
6589
                        _LMItemNote.Commit();
6590
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6591
                        if (_LMAAttribute != null)
6592
                        {
6593
                            _LMAAttribute.set_Value(note.VALUE);
6594
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6595
                            _LMItemNote.Commit();
6596

    
6597
                            ReleaseCOMObjects(_LMAAttribute);
6598
                            ReleaseCOMObjects(_LMItemNote);
6599
                        }
6600
                    }
6601
                }
6602

    
6603
                ReleaseCOMObjects(symbol);
6604
                symbol = null;
6605
                ReleaseCOMObjects(_LMItemNote);
6606
                _LMItemNote = null;
6607
                ReleaseCOMObjects(_LMAAttribute);
6608
                _LMAAttribute = null;
6609
                ReleaseCOMObjects(_LMSymbol);
6610
                _LMSymbol = null;
6611
            }
6612

    
6613
            endList.Add(note);
6614
        }
6615

    
6616
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
6617
        {
6618
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6619
            if (modelItem != null)
6620
            {
6621
                foreach (LMRepresentation rep in modelItem.Representations)
6622
                {
6623
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
6624
                    {
6625
                        LMConnector connector = dataSource.GetConnector(rep.Id);
6626
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
6627
                        {
6628
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
6629
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6630
                            if (modelItemIds.Count == 1)
6631
                            {
6632
                                string joinModelItemId = modelItemIds[0];
6633
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6634
                                if (survivorId != null)
6635
                                    break;
6636
                            }
6637
                        }
6638
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
6639
                        {
6640
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
6641
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6642
                            if (modelItemIds.Count == 1)
6643
                            {
6644
                                string joinModelItemId = modelItemIds[0];
6645
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6646
                                if (survivorId != null)
6647
                                    break;
6648
                            }
6649
                        }
6650
                    }
6651
                }
6652
            }
6653
        }
6654

    
6655
        /// <summary>
6656
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
6657
        /// </summary>
6658
        /// <param name="x"></param>
6659
        /// <param name="y"></param>
6660
        /// <param name="originX"></param>
6661
        /// <param name="originY"></param>
6662
        /// <param name="SPPIDLabelLocation"></param>
6663
        /// <param name="location"></param>
6664
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDEtcLocationInfo SPPIDLabelLocation, Location location)
6665
        {
6666
            if (location == Location.None)
6667
            {
6668
                x = originX;
6669
                y = originY;
6670
            }
6671
            else
6672
            {
6673
                if (location.HasFlag(Location.Center))
6674
                {
6675
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
6676
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
6677
                }
6678

    
6679
                if (location.HasFlag(Location.Left))
6680
                    x = SPPIDLabelLocation.X1;
6681
                else if (location.HasFlag(Location.Right))
6682
                    x = SPPIDLabelLocation.X2;
6683

    
6684
                if (location.HasFlag(Location.Down))
6685
                    y = SPPIDLabelLocation.Y1;
6686
                else if (location.HasFlag(Location.Up))
6687
                    y = SPPIDLabelLocation.Y2;
6688
            }
6689
        }
6690

    
6691
        /// <summary>
6692
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
6693
        /// 1. Angle Valve
6694
        /// 2. 3개로 이루어진 Symbol Group
6695
        /// </summary>
6696
        /// <returns></returns>
6697
        private List<Symbol> GetPrioritySymbol()
6698
        {
6699
            DataTable symbolTable = document.SymbolTable;
6700
            // List에 순서대로 쌓는다.
6701
            List<Symbol> symbols = new List<Symbol>();
6702

    
6703
            // Angle Valve 부터
6704
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
6705
            {
6706
                if (!symbols.Contains(symbol))
6707
                {
6708
                    double originX = 0;
6709
                    double originY = 0;
6710

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

    
6715
                    SlopeType slopeType1 = SlopeType.None;
6716
                    SlopeType slopeType2 = SlopeType.None;
6717
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
6718
                    {
6719
                        double connectorX = 0;
6720
                        double connectorY = 0;
6721
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
6722
                        if (slopeType1 == SlopeType.None)
6723
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6724
                        else
6725
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6726
                    }
6727

    
6728
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
6729
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
6730
                        symbols.Add(symbol);
6731
                }
6732
            }
6733

    
6734
            List<Symbol> tempSymbols = new List<Symbol>();
6735
            // Conn 갯수 기준
6736
            foreach (var item in document.SYMBOLS)
6737
            {
6738
                if (!symbols.Contains(item))
6739
                    tempSymbols.Add(item);
6740
            }
6741
            tempSymbols.Sort(SPPIDUtil.SortSymbolPriority);
6742
            symbols.AddRange(tempSymbols);
6743

    
6744
            return symbols;
6745
        }
6746

    
6747
        private void SetPriorityLine(List<Line> lines)
6748
        {
6749
            lines.Sort(SortLinePriority);
6750

    
6751
            int SortLinePriority(Line a, Line b)
6752
            {
6753
                int childRetval = CompareChild(a, b);
6754
                if (childRetval != 0)
6755
                {
6756
                    return childRetval;
6757
                }
6758
                else
6759
                { 
6760
                    // Branch 없는것부터
6761
                    int branchRetval = CompareBranchLine(a, b);
6762
                    if (branchRetval != 0)
6763
                    {
6764
                        return branchRetval;
6765
                    }
6766
                    else
6767
                    {
6768
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
6769
                        int connItemRetval = CompareConnItem(a, b);
6770
                        if (connItemRetval != 0)
6771
                        {
6772
                            return connItemRetval;
6773
                        }
6774
                        else
6775
                        {
6776
                            // line 길이
6777
                            int lengthRetval = CompareLength(a, b);
6778
                            if (lengthRetval != 0)
6779
                            {
6780
                                return lengthRetval;
6781
                            }
6782
                            else
6783
                            {
6784
                                // Symbol 연결 갯수
6785
                                int connSymbolRetval = CompareConnSymbol(a, b);
6786
                                if (connSymbolRetval != 0)
6787
                                {
6788
                                    return connSymbolRetval;
6789
                                }
6790
                                else
6791
                                {
6792
                                    // ConnectedItem이 없는것
6793
                                    int noneConnRetval = CompareNoneConn(a, b);
6794
                                    if (noneConnRetval != 0)
6795
                                    {
6796
                                        return noneConnRetval;
6797
                                    }
6798
                                    else
6799
                                    {
6800

    
6801
                                    }
6802
                                }
6803
                            }
6804
                        }
6805
                    }
6806
                }
6807

    
6808
                return 0;
6809
            }
6810

    
6811
            int CompareChild(Line a, Line b)
6812
            {
6813
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6814
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
6815

    
6816
                // 내림차순
6817
                return countA.CompareTo(countB);
6818
            }
6819

    
6820
            int CompareConnSymbol(Line a, Line b)
6821
            {
6822
                List<Connector> connectorsA = a.CONNECTORS
6823
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6824
                    .ToList();
6825

    
6826
                List<Connector> connectorsB = b.CONNECTORS
6827
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6828
                    .ToList();
6829

    
6830
                // 내림차순
6831
                return connectorsA.Count.CompareTo(connectorsB.Count);
6832
            }
6833

    
6834
            int CompareLength(Line a, Line b)
6835
            {
6836
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6837
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6838

    
6839
                // 오름차순
6840
                return lengthB.CompareTo(lengthA);
6841
            }
6842

    
6843
            int CompareConnItem(Line a, Line b)
6844
            {
6845
                List<Connector> connectorsA = a.CONNECTORS
6846
                    .Where(conn => conn.ConnectedObject != null &&
6847
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6848
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6849
                    .ToList();
6850

    
6851
                List<Connector> connectorsB = b.CONNECTORS
6852
                    .Where(conn => conn.ConnectedObject != null &&
6853
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6854
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6855
                    .ToList();
6856

    
6857
                // 내림차순
6858
                return connectorsA.Count.CompareTo(connectorsB.Count);
6859
            }
6860

    
6861
            int CompareBranchLine(Line a, Line b)
6862
            {
6863
                List<Connector> connectorsA = a.CONNECTORS
6864
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6865
                    .ToList();
6866
                List<Connector> connectorsB = b.CONNECTORS
6867
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6868
                    .ToList();
6869

    
6870
                // 내림차순
6871
                return connectorsA.Count.CompareTo(connectorsB.Count);
6872
            }
6873

    
6874
            int CompareNoneConn(Line a, Line b)
6875
            {
6876
                List<Connector> connectorsA = a.CONNECTORS
6877
                    .Where(conn => conn.ConnectedObject == null)
6878
                    .ToList();
6879

    
6880
                List<Connector> connectorsB = b.CONNECTORS
6881
                    .Where(conn => conn.ConnectedObject == null)
6882
                    .ToList();
6883

    
6884
                // 내림차순
6885
                return connectorsA.Count.CompareTo(connectorsB.Count);
6886
            }
6887
        }
6888

    
6889
        private void SortText(List<Text> texts)
6890
        {
6891
            texts.Sort(Sort);
6892

    
6893
            int Sort(Text a, Text b)
6894
            {
6895
                int yRetval = CompareY(a, b);
6896
                if (yRetval != 0)
6897
                {
6898
                    return yRetval;
6899
                }
6900
                else
6901
                {
6902
                    return CompareX(a, b);
6903
                }
6904
            }
6905

    
6906
            int CompareY(Text a, Text b)
6907
            {
6908
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6909
            }
6910

    
6911
            int CompareX(Text a, Text b)
6912
            {
6913
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6914
            }
6915
        }
6916
        private void SortNote(List<Note> notes)
6917
        {
6918
            notes.Sort(Sort);
6919

    
6920
            int Sort(Note a, Note b)
6921
            {
6922
                int yRetval = CompareY(a, b);
6923
                if (yRetval != 0)
6924
                {
6925
                    return yRetval;
6926
                }
6927
                else
6928
                {
6929
                    return CompareX(a, b);
6930
                }
6931
            }
6932

    
6933
            int CompareY(Note a, Note b)
6934
            {
6935
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6936
            }
6937

    
6938
            int CompareX(Note a, Note b)
6939
            {
6940
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6941
            }
6942
        }
6943

    
6944
        private void SortBranchLines()
6945
        {
6946
            BranchLines.Sort(SortBranchLine);
6947

    
6948
            int SortBranchLine(Line a, Line b)
6949
            {
6950
                int childRetval = CompareChild(a, b);
6951
                if (childRetval != 0)
6952
                {
6953
                    return childRetval;
6954
                }
6955
                else
6956
                {
6957
                    int branchRetval = CompareChildBranch(a, b);
6958
                    if (branchRetval != 0)
6959
                    {
6960
                        return branchRetval;
6961
                    }
6962
                    else
6963
                    {
6964
                        // line 길이
6965
                        int lengthRetval = CompareLength(a, b);
6966
                        if (lengthRetval != 0)
6967
                        {
6968
                            return lengthRetval;
6969
                        }
6970
                    }
6971
                }
6972
                return 0;
6973
            }
6974

    
6975
            int CompareLength(Line a, Line b)
6976
            {
6977
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6978
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6979

    
6980
                // 오름차순
6981
                return lengthB.CompareTo(lengthA);
6982
            }
6983

    
6984
            int CompareChildBranch(Line a, Line b)
6985
            {
6986
                int countA = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
6987
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == a));
6988

    
6989
                int countB = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
6990
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == b));
6991

    
6992
                // 오름차순
6993
                return countB.CompareTo(countA);
6994
            }
6995

    
6996
            int CompareChild(Line a, Line b)
6997
            {
6998
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6999
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
7000

    
7001
                // 내림차순
7002
                return countA.CompareTo(countB);
7003
            }
7004
        }
7005

    
7006
        private string GetSPPIDFileName(LMModelItem modelItem)
7007
        {
7008
            string symbolPath = null;
7009
            foreach (LMRepresentation rep in modelItem.Representations)
7010
            {
7011
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
7012
                {
7013
                    symbolPath = rep.get_FileName();
7014
                    break;
7015
                }
7016
            }
7017
            return symbolPath;
7018
        }
7019

    
7020
        private string GetSPPIDFileName(string modelItemId)
7021
        {
7022
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
7023
            string symbolPath = null;
7024
            foreach (LMRepresentation rep in modelItem.Representations)
7025
            {
7026
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
7027
                {
7028
                    symbolPath = rep.get_FileName();
7029
                    break;
7030
                }
7031
            }
7032
            ReleaseCOMObjects(modelItem);
7033
            return symbolPath;
7034
        }
7035

    
7036
        /// <summary>
7037
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
7038
        /// </summary>
7039
        /// <param name="graphicOID"></param>
7040
        /// <param name="milliseconds"></param>
7041
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
7042
        {
7043
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
7044
            {
7045
                double minX = 0;
7046
                double minY = 0;
7047
                double maxX = 0;
7048
                double maxY = 0;
7049
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
7050
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
7051

    
7052
                Thread.Sleep(milliseconds);
7053
            }
7054
        }
7055

    
7056
        /// <summary>
7057
        /// ComObject를 Release
7058
        /// </summary>
7059
        /// <param name="objVars"></param>
7060
        public void ReleaseCOMObjects(params object[] objVars)
7061
        {
7062
            if (objVars != null)
7063
            {
7064
                int intNewRefCount = 0;
7065
                foreach (object obj in objVars)
7066
                {
7067
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
7068
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
7069
                }
7070
            }
7071
        }
7072

    
7073
        /// IDisposable 구현
7074
        ~AutoModeling()
7075
        {
7076
            this.Dispose(false);
7077
        }
7078

    
7079
        private bool disposed;
7080
        public void Dispose()
7081
        {
7082
            this.Dispose(true);
7083
            GC.SuppressFinalize(this);
7084
        }
7085

    
7086
        protected virtual void Dispose(bool disposing)
7087
        {
7088
            if (this.disposed) return;
7089
            if (disposing)
7090
            {
7091
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
7092
            }
7093
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
7094
            this.disposed = true;
7095
        }
7096
    }
7097
}
클립보드 이미지 추가 (최대 크기: 500 MB)