프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 3fbf99d3

이력 | 보기 | 이력해설 | 다운로드 (334 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
            SetFlowAllLine();
792
        }
793
        private void RunSpecBreakModeling()
794
        {
795
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
796
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
797
            foreach (var item in document.SpecBreaks)
798
                try
799
                {
800
                    SpecBreakModeling(item);
801
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
802
                }
803
                catch (Exception ex)
804
                {
805
                    Log.Write("Error in SpecBreakModeling");
806
                    Log.Write("UID : " + item.UID);
807
                    Log.Write(ex.Message);
808
                    Log.Write(ex.StackTrace);
809
                }
810
        }
811
        private void RunJoinRunForSameConnector()
812
        {
813
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
814
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
815
            foreach (var line in document.LINES)
816
            {
817
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
818
                List<List<double[]>> result = new List<List<double[]>>();
819
                foreach (var item in vertices)
820
                {
821
                    ReleaseCOMObjects(item.Key);
822
                    result.Add(item.Value);
823
                }
824
                line.SPPID.Vertices = result;
825
                vertices = null;
826
            }
827

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

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

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

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

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

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

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

    
1095
            }
1096

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

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

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

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

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

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

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

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

    
1263
                LMDrawings drawings = new LMDrawings();
1264
                drawings.Collect(dataSource, Filter: filter);
1265

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

    
1292
                        drawingAttributeDT.Dispose();
1293
                    }
1294

    
1295
                    ReleaseCOMObjects(drawing);
1296
                }
1297

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

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

    
1318
        private void SetBorderFile()
1319
        {
1320
            ETCSetting setting = ETCSetting.GetInstance();
1321

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

    
1332
                }
1333
            }
1334
        }
1335

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

    
1346
            List<string> drawingNameList = new List<string>();
1347
            List<string> drawingNumberList = new List<string>();
1348

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

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

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

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

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

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

    
1439
            LMSymbol _LMSymbol = null;
1440

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

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

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

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

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

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

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

    
1481
            if (_LMSymbol != null)
1482
            {
1483
                _LMSymbol.Commit();
1484

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

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

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

    
1511
                foreach (var item in symbol.ChildSymbols)
1512
                    CreateChildSymbol(item, _LMSymbol, symbol);
1513

    
1514
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1515
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1516

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

    
1524
                double xGap = symbol.SPPID.SPPID_X - symbol.SPPID.ORIGINAL_X;
1525
                double yGap = symbol.SPPID.SPPID_Y - symbol.SPPID.ORIGINAL_Y;
1526

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

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

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

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

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

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

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

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

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

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

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

    
1708
            return info;
1709
        }
1710

    
1711
        private void RemoveSymbol(Symbol symbol)
1712
        {
1713
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1714
            {
1715
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1716
                if (_LMSymbol != null)
1717
                {
1718
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1719
                    ReleaseCOMObjects(_LMSymbol);
1720
                }
1721
            }
1722

    
1723
            symbol.SPPID.RepresentationId = string.Empty;
1724
            symbol.SPPID.ModelItemID = string.Empty;
1725
            symbol.SPPID.SPPID_X = double.NaN;
1726
            symbol.SPPID.SPPID_Y = double.NaN;
1727
            symbol.SPPID.SPPID_Min_X = double.NaN;
1728
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1729
            symbol.SPPID.SPPID_Max_X = double.NaN;
1730
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1731
        }
1732

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

    
1747
                symbol.SPPID.RepresentationId = string.Empty;
1748
                symbol.SPPID.ModelItemID = string.Empty;
1749
                symbol.SPPID.SPPID_X = double.NaN;
1750
                symbol.SPPID.SPPID_Y = double.NaN;
1751
                symbol.SPPID.SPPID_Min_X = double.NaN;
1752
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1753
                symbol.SPPID.SPPID_Max_X = double.NaN;
1754
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1755
            }
1756
        }
1757

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

    
1769
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1770

    
1771
            double[] range = null;
1772
            List<double[]> points = new List<double[]>();
1773
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1774
            double x1 = range[0];
1775
            double y1 = range[1];
1776
            double x2 = range[2];
1777
            double y2 = range[3];
1778

    
1779
            // Origin 기준 Connector의 위치차이
1780
            double sceneX = 0;
1781
            double sceneY = 0;
1782
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1783
            double originX = 0;
1784
            double originY = 0;
1785
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1786
            double gapX = originX - sceneX;
1787
            double gapY = originY - sceneY;
1788

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

    
1796
            double percentX = (x2 - x1) / sizeWidth;
1797
            double percentY = (y2 - y1) / sizeHeight;
1798

    
1799
            double SPPIDgapX = gapX * percentX;
1800
            double SPPIDgapY = gapY * percentY;
1801

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

    
1817
            ReleaseCOMObjects(_TargetItem);
1818
        }
1819

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

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

    
1852
            for (int i = 1; i < 30; i++)
1853
            {
1854
                double connX = 0;
1855
                double connY = 0;
1856
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1857
                    points.Add(new double[] { connX, connY });
1858
            }
1859

    
1860
            foreach (var childSymbol in symbol.ChildSymbols)
1861
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1862

    
1863
            ReleaseCOMObjects(_TargetItem);
1864
        }
1865

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

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

    
1950
                if (!bOnlySymbol)
1951
                {
1952
                    foreach (var childSymbol in symbol.ChildSymbols)
1953
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1954
                }
1955
                ReleaseCOMObjects(_TargetItem);
1956
            }
1957
        }
1958

    
1959
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1960
        {
1961
            if (labelPersist != null)
1962
            {
1963
                double x1 = double.MaxValue;
1964
                double y1 = double.MaxValue;
1965
                double x2 = double.MinValue;
1966
                double y2 = double.MinValue;
1967
                range = new double[] { x1, y1, x2, y2 };
1968

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

    
1987
                            range = new double[] { x1, y1, x2, y2 };
1988
                        }
1989
                    }
1990
                }
1991

    
1992
            }
1993
        }
1994

    
1995
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1996
        {
1997
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1998
            foreach (var symbol in symbols)
1999
            {
2000
                double[] symbolRange = null;
2001
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
2002

    
2003
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
2004
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
2005
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
2006
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
2007

    
2008
                foreach (var childSymbol in symbol.ChildSymbols)
2009
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
2010
            }
2011

    
2012
            range = tempRange;
2013
        }
2014

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

    
2036
                for (int i = 1; i < int.MaxValue; i++)
2037
                {
2038
                    double connX = 0;
2039
                    double connY = 0;
2040
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
2041
                        points.Add(new double[] { connX, connY });
2042
                    else
2043
                        break;
2044
                }
2045

    
2046
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
2047
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
2048

    
2049
                ReleaseCOMObjects(_ChildSymbol);
2050
            }
2051
        }
2052

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

    
2069
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
2070
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
2071
                ReleaseCOMObjects(_ChildSymbol);
2072
            }
2073
        }
2074

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

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

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

    
2112
                        //Leader 선 센터로
2113
                        if (_LMLabelPresist != null)
2114
                        {
2115
                            // Target Item에 Label의 Attribute Input
2116
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
2117

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

    
2146
                                        if (result)
2147
                                            break;
2148
                                    }
2149

    
2150
                                    if (result)
2151
                                        break;
2152
                                }
2153
                            }
2154

    
2155
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
2156
                            _LMLabelPresist.Commit();
2157
                            ReleaseCOMObjects(_LMLabelPresist);
2158
                        }
2159

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

    
2173
                        // LEADER Line 검사
2174
                        bool leaderLine = false;
2175
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
2176
                        if (symbolMapping != null)
2177
                            leaderLine = symbolMapping.LEADERLINE;
2178

    
2179
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: symbol.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
2180
                        if (_LMLabelPresist != null)
2181
                        {
2182
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
2183
                            _LMLabelPresist.Commit();
2184
                            ReleaseCOMObjects(_LMLabelPresist);
2185
                        }
2186
                        ReleaseCOMObjects(connectedLMConnector);
2187
                    }
2188

    
2189
                    foreach (var item in connectorVertices)
2190
                        if (item.Key != null)
2191
                            ReleaseCOMObjects(item.Key);
2192
                }
2193
            }
2194
        }
2195

    
2196
        /// <summary>
2197
        /// Equipment를 실제로 Modeling 메서드
2198
        /// </summary>
2199
        /// <param name="equipment"></param>
2200
        private void EquipmentModeling(Equipment equipment)
2201
        {
2202
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
2203
                return;
2204

    
2205
            LMSymbol _LMSymbol = null;
2206
            LMSymbol targetItem = null;
2207
            string mappingPath = equipment.SPPID.MAPPINGNAME;
2208
            double x = equipment.SPPID.ORIGINAL_X;
2209
            double y = equipment.SPPID.ORIGINAL_Y;
2210
            int mirror = 0;
2211
            double angle = equipment.ANGLE;
2212

    
2213
            // Mirror 계산
2214
            if (equipment.FLIP == 1)
2215
            {
2216
                mirror = 1;
2217
                if (angle == Math.PI || angle == 0)
2218
                    angle += Math.PI;
2219
            }
2220

    
2221
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
2222

    
2223
            Connector connector = equipment.CONNECTORS.Find(conn =>
2224
            !string.IsNullOrEmpty(conn.CONNECTEDITEM) &&
2225
            conn.CONNECTEDITEM != "None" &&
2226
            conn.ConnectedObject.GetType() == typeof(Equipment));
2227

    
2228
            if (connector != null)
2229
            {
2230
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
2231
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
2232
                if (connEquipment != null)
2233
                {
2234
                    //if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2235
                    //    EquipmentModeling(connEquipment);
2236

    
2237
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2238
                    {
2239
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
2240
                        if (targetItem != null)
2241
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2242
                        else
2243
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2244
                    }
2245
                    else
2246
                    {
2247
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2248
                    }
2249
                }
2250
                else if (connVendorPackage != null)
2251
                {
2252
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
2253
                    {
2254
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
2255
                        if (targetItem != null)
2256
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2257
                        else
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
            else
2267
            {
2268
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2269
            }
2270

    
2271
            if (_LMSymbol != null)
2272
            {
2273
                _LMSymbol.Commit();
2274
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2275
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
2276
                ReleaseCOMObjects(_LMSymbol);
2277
            }
2278

    
2279
            if (targetItem != null)
2280
            {
2281
                ReleaseCOMObjects(targetItem);
2282
            }
2283

    
2284
            ReleaseCOMObjects(_LMSymbol);
2285
        }
2286

    
2287
        private void VendorPackageModeling(VendorPackage vendorPackage)
2288
        {
2289
            ETCSetting setting = ETCSetting.GetInstance();
2290
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2291
            {
2292
                string symbolPath = setting.VendorPackageSymbolPath;
2293
                double x = vendorPackage.SPPID.ORIGINAL_X;
2294
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2295

    
2296
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2297
                if (symbol != null)
2298
                {
2299
                    symbol.Commit();
2300
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2301
                }
2302

    
2303
                ReleaseCOMObjects(symbol);
2304
                symbol = null;
2305
            }
2306
        }
2307

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

    
2317
            int styleCount = radApp.ActiveDocument.SmartFrame2dStyles.Count(c => c.Name.StartsWith(styleName));
2318
            styleName = string.Format("{0}_{1}", styleName, styleCount);
2319
            Ingr.RAD2D.SmartFrame2dStyle StyleConverter = radApp.ActiveDocument.SmartFrame2dStyles.Add(styleName, "");
2320

    
2321
            Ingr.RAD2D.SmartFrame2d smartFrame = radApp.ActiveDocument.ActiveSheet.SmartFrames2d.AddBy2Points(styleName, 0.01, 0.01, 0.1, 0.1, false, filePath);
2322
            smartFrame.BorderVisible = false;
2323
            smartFrame.SetLayerDisplay("default", true);
2324

    
2325
            double oMinx = 0, oMinY = 0, oMaxX = 0, oMaxY = 0;
2326
            smartFrame.Range(out oMinx, out oMinY, out oMaxX, out oMaxY);
2327
            double cWidth = oMaxX - oMinx;
2328
            double cHeight = oMaxY - oMinY;
2329
            double height = Math.Abs(graphic.SPPIDGraphicLocation.Y2 - graphic.SPPIDGraphicLocation.Y1);
2330
            double width = Math.Abs(graphic.SPPIDGraphicLocation.X2 - graphic.SPPIDGraphicLocation.X1);
2331
            double scaleFactor = width / cWidth;
2332
            smartFrame.ScaleFactor = scaleFactor;
2333
            smartFrame.SetOrigin(graphic.SPPIDGraphicLocation.X1, graphic.SPPIDGraphicLocation.Y1);
2334
        }
2335

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

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

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

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

    
2422
                                List<Symbol> group = new List<Symbol>();
2423
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2424
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2425
                                List<Symbol> endModelingGroup = new List<Symbol>();
2426
                                if (priority != null)
2427
                                {
2428
                                    SymbolGroupModeling(priority, group);
2429

    
2430
                                    // Range 겹치는지 확인해야함
2431
                                    double[] prevRange = null;
2432
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2433
                                    double[] groupRange = null;
2434
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2435

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

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

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

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

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

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

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

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

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

    
2584
            ReleaseCOMObjects(_LMSymbol);
2585
        }
2586
        double index = 0;
2587
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2588
        {
2589
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2590
                return;
2591

    
2592
            List<Line> group = new List<Line>();
2593
            GetConnectedLineGroup(line, group);
2594
            if (!BranchLines.Contains(line))
2595
                LineCoordinateCorrection(group);
2596

    
2597
            for (int i = 0; i < group.Count; i++)
2598
            {
2599
                string targetModelItemId = null;
2600
                var currentLine = group[i];
2601

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

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

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

    
2729
                            placeRunInputs.AddPoint(x, y);
2730

    
2731
                            if (currentLine.CONNECTORS.IndexOf(connector) == 1)
2732
                            {
2733
                                index += 0.01;
2734
                                if (currentLine.SlopeType == SlopeType.HORIZONTAL)
2735
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2736
                                else if (currentLine.SlopeType == SlopeType.VERTICAL)
2737
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2738
                                else
2739
                                {
2740
                                    Line nextLine = currentLine.CONNECTORS[1].ConnectedObject as Line;
2741
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2742
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2743
                                    else
2744
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2745
                                }
2746
                            }
2747
                        }
2748
                    }
2749
                    else
2750
                        placeRunInputs.AddPoint(x, y);
2751
                }
2752

    
2753
                LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
2754
                if (lMConnector != null)
2755
                {
2756
                    lMConnector.Commit();
2757
                    if (!string.IsNullOrWhiteSpace(targetModelItemId))
2758
                    {
2759
                        LMModelItem modelItem1 = dataSource.GetModelItem(targetModelItemId);
2760
                        LMModelItem modelItem2 = dataSource.GetModelItem(lMConnector.ModelItemID);
2761
                        _LMAItem item1 = modelItem1.AsLMAItem();
2762
                        _LMAItem item2 = modelItem2.AsLMAItem();
2763
                        _placement.PIDJoinRuns(item1, item2);
2764
                        item1.Commit();
2765
                        item2.Commit();
2766
                        ReleaseCOMObjects(item1);
2767
                        ReleaseCOMObjects(item2);
2768
                        ReleaseCOMObjects(modelItem1);
2769
                        ReleaseCOMObjects(modelItem2);
2770
                    }
2771

    
2772
                    currentLine.SPPID.ModelItemId = lMConnector.ModelItemID;
2773

    
2774
                    bool bRemodelingStart = false;
2775
                    if (lMSymbolStart != null)
2776
                        NeedReModeling(currentLine, lMSymbolStart, ref bRemodelingStart);
2777
                    bool bRemodelingEnd = false;
2778
                    if (lMSymbolEnd != null)
2779
                        NeedReModeling(currentLine, lMSymbolEnd, ref bRemodelingEnd);
2780

    
2781
                    if (bRemodelingStart || bRemodelingEnd)
2782
                        ReModelingLine(currentLine, lMConnector, lMSymbolStart, lMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2783

    
2784
                    FlowMarkModeling(currentLine);
2785

    
2786
                    SetFlowUpstream(lMConnector.ModelItemID);
2787
                    ReleaseCOMObjects(lMConnector);
2788
                }
2789
                else if (!isBranchModeling)
2790
                {
2791
                    Log.Write("Main Line Modeling : " + currentLine.UID);
2792
                }
2793

    
2794
                List<object> removeLines = currentLine.CONNECTORS.FindAll(x =>
2795
                x.ConnectedObject != null &&
2796
                x.ConnectedObject.GetType() == typeof(Line) &&
2797
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2798
                .Select(x => x.ConnectedObject)
2799
                .ToList();
2800

    
2801
                foreach (var item in removeLines)
2802
                    RemoveLineForModeling(item as Line);
2803

    
2804
                ReleaseCOMObjects(lMAItem);
2805
                lMAItem = null;
2806
                ReleaseCOMObjects(placeRunInputs);
2807
                placeRunInputs = null;
2808
                ReleaseCOMObjects(lMSymbolStart);
2809
                lMSymbolStart = null;
2810
                ReleaseCOMObjects(lMSymbolEnd);
2811
                lMSymbolEnd = null;
2812
            }
2813
        }
2814

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

    
2876
            LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
2877
            if (lMConnector != null)
2878
            {
2879
                lMConnector.Commit();
2880

    
2881
                SetFlowUpstream(lMConnector.ModelItemID);
2882
            }
2883

    
2884
            ReleaseCOMObjects(lMAItem);
2885
            lMAItem = null;
2886
            ReleaseCOMObjects(placeRunInputs);
2887
            placeRunInputs = null;
2888
            ReleaseCOMObjects(lMSymbolStart);
2889
            lMSymbolStart = null;
2890
            ReleaseCOMObjects(lMSymbolEnd);
2891
            lMSymbolEnd = null;
2892

    
2893
            return lMConnector;
2894
        }
2895

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

    
2924
                ReleaseCOMObjects(modelItem);
2925
            }
2926
        }
2927

    
2928
        private void RemoveLine(Line line)
2929
        {
2930
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2931
            if (modelItem != null)
2932
            {
2933
                foreach (LMRepresentation rep in modelItem.Representations)
2934
                {
2935
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2936
                        _placement.PIDRemovePlacement(rep);
2937
                }
2938
                ReleaseCOMObjects(modelItem);
2939
            }
2940
            line.SPPID.ModelItemId = null;
2941
        }
2942

    
2943
        private void GetConnectedLineGroup(Line line, List<Line> group)
2944
        {
2945
            if (!group.Contains(line))
2946
                group.Add(line);
2947

    
2948
            foreach (var connector in line.CONNECTORS)
2949
            {
2950
                if (connector.ConnectedObject != null &&
2951
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2952
                    !group.Contains(connector.ConnectedObject) &&
2953
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2954
                {
2955
                    Line connLine = connector.ConnectedObject as Line;
2956
                    if (line.CONNECTORS.IndexOf(connector) == 0
2957
                    && (!SPPIDUtil.IsBranchLine(connLine, line)))
2958
                    {
2959

    
2960
                        group.Insert(group.IndexOf(line), connLine);
2961
                        GetConnectedLineGroup(connLine, group);
2962
                    }
2963
                    else if (line.CONNECTORS.IndexOf(connector) == 1 && !SPPIDUtil.IsBranchLine(connLine, line))
2964
                    {
2965
                        group.Add(connLine);
2966
                        GetConnectedLineGroup(connLine, group);
2967
                    }
2968
                }
2969
            }
2970
        }
2971

    
2972
        private void LineCoordinateCorrection(List<Line> group)
2973
        {
2974
            // 순서대로 전 Item 기준 정렬
2975
            LineCoordinateCorrectionByStart(group);
2976

    
2977
            // 역으로 심볼이 있을 경우 좌표 보정
2978
            LineCoordinateCorrectionForLastLine(group);
2979
        }
2980

    
2981
        private void LineCoordinateCorrectionByStart(List<Line> group)
2982
        {
2983
            for (int i = 0; i < group.Count; i++)
2984
            {
2985
                Line line = group[i];
2986
                if (i == 0)
2987
                {
2988
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2989
                    if (symbolConnector != null)
2990
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2991
                }
2992
                else if (i != 0)
2993
                {
2994
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2995
                }
2996
            }
2997
        }
2998

    
2999
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
3000
        {
3001
            Line checkLine = group[group.Count - 1];
3002
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
3003
            if (lastSymbolConnector != null)
3004
            {
3005
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
3006
                for (int i = group.Count - 2; i >= 0; i--)
3007
                {
3008
                    Line refLine = group[i + 1];
3009
                    Line changeline = group[i];
3010
                    LineCoordinateCorrectionByConnItem(changeline, refLine);
3011
                }
3012
            }
3013
        }
3014

    
3015
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
3016
        {
3017
            double x = 0;
3018
            double y = 0;
3019
            if (connItem.GetType() == typeof(Symbol))
3020
            {
3021
                Symbol targetSymbol = connItem as Symbol;
3022
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
3023
                if (targetConnector != null)
3024
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
3025
                else
3026
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
3027
            }
3028
            else if (connItem.GetType() == typeof(Line))
3029
            {
3030
                Line targetLine = connItem as Line;
3031
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
3032
            }
3033

    
3034
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
3035
        }
3036
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
3037
        {
3038
            bool isReverseX = line.SPPID.END_X - line.SPPID.START_X < 0;
3039
            bool isReverseY = line.SPPID.END_Y - line.SPPID.START_Y < 0;
3040
            double minLength = GridSetting.GetInstance().Length * 0.5;
3041
            double minLengthX = minLength * (!isReverseX ? 1 : -1);
3042
            double minLengthY = minLength * (!isReverseY ? 1 : -1);
3043

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

    
3094
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
3095
        {
3096
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3097
            int index = line.CONNECTORS.IndexOf(connector);
3098
            if (index == 0)
3099
            {
3100
                line.SPPID.START_X = x;
3101
                if (line.SlopeType == SlopeType.VERTICAL)
3102
                    line.SPPID.END_X = x;
3103
            }
3104
            else
3105
            {
3106
                line.SPPID.END_X = x;
3107
                if (line.SlopeType == SlopeType.VERTICAL)
3108
                    line.SPPID.START_X = x;
3109
            }
3110
        }
3111

    
3112
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
3113
        {
3114
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3115
            int index = line.CONNECTORS.IndexOf(connector);
3116
            if (index == 0)
3117
            {
3118
                line.SPPID.START_Y = y;
3119
                if (line.SlopeType == SlopeType.HORIZONTAL)
3120
                    line.SPPID.END_Y = y;
3121
            }
3122
            else
3123
            {
3124
                line.SPPID.END_Y = y;
3125
                if (line.SlopeType == SlopeType.HORIZONTAL)
3126
                    line.SPPID.START_Y = y;
3127
            }
3128
        }
3129

    
3130
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
3131
        {
3132
            if (symbol != null)
3133
            {
3134
                string repID = symbol.AsLMRepresentation().Id;
3135
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
3136
                string lineUID = line.UID;
3137

    
3138
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
3139
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
3140
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
3141

    
3142
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
3143
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
3144
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
3145

    
3146
                if (startSpecBreak != null || startEndBreak != null)
3147
                    result = true;
3148
            }
3149
        }
3150

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

    
3178
            List<double[]> vertices = new List<double[]>();
3179
            for (int i = 1; i <= verticesCount; i++)
3180
            {
3181
                double x = 0;
3182
                double y = 0;
3183
                lineStringGeometry.GetVertex(i, ref x, ref y);
3184
                vertices.Add(new double[] { x, y });
3185
            }
3186

    
3187
            for (int i = 0; i < vertices.Count; i++)
3188
            {
3189
                double[] points = vertices[i];
3190
                // 시작 심볼이 있고 첫번째 좌표일 때
3191
                if (startSymbol != null && i == 0)
3192
                {
3193
                    if (bStart)
3194
                    {
3195
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
3196
                        if (slopeType == SlopeType.HORIZONTAL)
3197
                            placeRunInputs.AddPoint(points[0], -0.1);
3198
                        else if (slopeType == SlopeType.VERTICAL)
3199
                            placeRunInputs.AddPoint(-0.1, points[1]);
3200
                        else
3201
                            placeRunInputs.AddPoint(points[0], -0.1);
3202

    
3203
                        placeRunInputs.AddPoint(points[0], points[1]);
3204
                    }
3205
                    else
3206
                    {
3207
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
3208
                    }
3209
                }
3210
                // 마지막 심볼이 있고 마지막 좌표일 때
3211
                else if (endSymbol != null && i == vertices.Count - 1)
3212
                {
3213
                    if (bEnd)
3214
                    {
3215
                        _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3216
                        PlaceRunInputs placeFirstRunInputs = new PlaceRunInputs();
3217

    
3218
                        placeFirstRunInputs.AddPoint(points[0], points[1]);
3219
                        placeFirstRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3220

    
3221
                        string otherSymbolPath = symbolPath;
3222
                        Symbol symbolDef = document.SYMBOLS.Find(f => f.SPPID.RepresentationId == endSymbol.AsLMRepresentation().Id);
3223
                        if (symbolDef != null)
3224
                        {
3225
                            Connector otherConn = symbolDef.CONNECTORS.Find(f => f.ConnectedObject != null && f.ConnectedObject.GetType() == typeof(Line) && ((Line)f.ConnectedObject).UID != line.UID);
3226
                            if (otherConn != null)
3227
                            {
3228
                                otherSymbolPath = ((Line)otherConn.ConnectedObject).SPPID.MAPPINGNAME;
3229
                            }
3230
                        }
3231

    
3232
                        _LMAItem lMAFirstItem = _placement.PIDCreateItem(otherSymbolPath);
3233
                        newFirstConnector = _placement.PIDPlaceRun(lMAFirstItem, placeFirstRunInputs);
3234
                        newFirstConnector.Commit();
3235

    
3236
                        SetFlowUpstream(newFirstConnector.ModelItemID);
3237

    
3238
                        placeRunInputs.AddConnectorTarget(newFirstConnector, points[0], points[1], diagonal);
3239
                        ReleaseCOMObjects(placeFirstRunInputs);
3240
                        ReleaseCOMObjects(lMAFirstItem);
3241
                    }
3242
                    else
3243
                    {
3244
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3245
                    }
3246
                }
3247
                // 첫번째이며 시작 심볼이 아니고 Connector일 경우
3248
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
3249
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
3250
                // 마지막이며 마지막 심볼이 아니고 Connector일 경우
3251
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
3252
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
3253
                else
3254
                    placeRunInputs.AddPoint(points[0], points[1]);
3255
            }
3256

    
3257
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3258
            newConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3259

    
3260
            ReleaseCOMObjects(placeRunInputs);
3261
            ReleaseCOMObjects(lMAItem);
3262
            ReleaseCOMObjects(modelItem);
3263

    
3264
            if (newConnector != null)
3265
            {
3266
                newConnector.Commit();
3267
                SetFlowUpstream(newConnector.ModelItemID);
3268

    
3269
                if (startSymbol != null && bStart)
3270
                {
3271
                    lMAItem = _placement.PIDCreateItem(symbolPath);
3272
                    placeRunInputs = new PlaceRunInputs();
3273
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
3274
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
3275
                    LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3276
                    if (lMConnector != null)
3277
                    {
3278
                        lMConnector.Commit();
3279
                        RemoveConnectorForReModelingLine(newConnector);
3280
                        SetFlowUpstream(lMConnector.ModelItemID);
3281

    
3282
                        ReleaseCOMObjects(lMConnector);
3283
                    }
3284
                    ReleaseCOMObjects(placeRunInputs);
3285
                    ReleaseCOMObjects(lMAItem);
3286
                }
3287

    
3288
                if (endSymbol != null && bEnd)
3289
                {
3290
                    ReleaseCOMObjects(newFirstConnector);
3291
                    ReleaseCOMObjects(placeRunInputs);
3292
                    ReleaseCOMObjects(lMAItem);
3293
                }
3294

    
3295
                line.SPPID.ModelItemId = newConnector.ModelItemID;
3296
                ReleaseCOMObjects(newConnector);
3297
            }
3298

    
3299
            ReleaseCOMObjects(modelItem);
3300
        }
3301

    
3302
        private void SetFlowUpstream(dynamic modelItemID)
3303
        {
3304
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
3305
            if (modelItem != null)
3306
            {
3307
                LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
3308
                if (attribute != null)
3309
                    attribute.set_Value("End 1 is upstream (Inlet)");
3310
                modelItem.Commit();
3311
                ReleaseCOMObjects(modelItem);
3312
            }
3313
        }
3314
        private void SetFlowAllLine(string modelItemID = "")
3315
        {
3316
            List<Line> lineList = null;
3317
            if (!string.IsNullOrWhiteSpace(modelItemID))
3318
            {
3319
                lineList = document.LINES.FindAll(z => z.SPPID.ModelItemId == modelItemID).ToList();
3320
            }
3321
            else
3322
            {
3323
                lineList = document.LINES;
3324
            }
3325
            foreach (var line in lineList)
3326
            {
3327
                foreach (var repId in line.SPPID.Representations)
3328
                {
3329
                    LMConnector _connector = dataSource.GetConnector(repId);
3330
                    if (_connector != null && _connector.get_ItemStatus() == "Active")
3331
                    {
3332
                        if (line.SPPID.ModelItemId != _connector.ModelItemID)
3333
                        {
3334
                            line.SPPID.ModelItemId = _connector.ModelItemID;
3335
                            line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3336
                        }
3337
                    }
3338
                    SetFlowUpstream(_connector.ModelItemID);
3339
                    ReleaseCOMObjects(_connector);
3340
                }
3341
            }
3342
        }
3343
        /// <summary>
3344
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
3345
        /// </summary>
3346
        /// <param name="connector"></param>
3347
        private void RemoveConnectorForReModelingLine(LMConnector connector)
3348
        {
3349
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
3350
            foreach (var item in dicVertices)
3351
            {
3352
                if (item.Value.Count == 2)
3353
                {
3354
                    bool result = false;
3355
                    foreach (var point in item.Value)
3356
                    {
3357
                        if (point[0] < 0 || point[1] < 0)
3358
                        {
3359
                            result = true;
3360
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
3361
                            break;
3362
                        }
3363
                    }
3364

    
3365
                    if (result)
3366
                        break;
3367
                }
3368
            }
3369
            foreach (var item in dicVertices)
3370
                ReleaseCOMObjects(item.Key);
3371
        }
3372

    
3373
        /// <summary>
3374
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
3375
        /// </summary>
3376
        /// <param name="symbol"></param>
3377
        /// <param name="line"></param>
3378
        /// <returns></returns>
3379
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
3380
        {
3381
            LMSymbol _LMSymbol = null;
3382
            foreach (var connector in symbol.CONNECTORS)
3383
            {
3384
                if (connector.CONNECTEDITEM == line.UID)
3385
                {
3386
                    if (connector.Index == 0)
3387
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3388
                    else
3389
                    {
3390
                        ChildSymbol child = null;
3391
                        foreach (var childSymbol in symbol.ChildSymbols)
3392
                        {
3393
                            if (childSymbol.Connectors.Contains(connector))
3394
                                child = childSymbol;
3395
                            else
3396
                                child = GetChildSymbolByConnector(childSymbol, connector);
3397

    
3398
                            if (child != null)
3399
                                break;
3400
                        }
3401

    
3402
                        if (child != null)
3403
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3404
                    }
3405

    
3406
                    break;
3407
                }
3408
            }
3409

    
3410
            return _LMSymbol;
3411
        }
3412

    
3413
        /// <summary>
3414
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3415
        /// </summary>
3416
        /// <param name="item"></param>
3417
        /// <param name="connector"></param>
3418
        /// <returns></returns>
3419
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3420
        {
3421
            foreach (var childSymbol in item.ChildSymbols)
3422
            {
3423
                if (childSymbol.Connectors.Contains(connector))
3424
                    return childSymbol;
3425
                else
3426
                    return GetChildSymbolByConnector(childSymbol, connector);
3427
            }
3428

    
3429
            return null;
3430
        }
3431

    
3432
        /// <summary>
3433
        /// EndBreak 모델링 메서드
3434
        /// </summary>
3435
        /// <param name="endBreak"></param>
3436
        private void EndBreakModeling(EndBreak endBreak)
3437
        {
3438
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3439
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3440

    
3441
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3442
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3443
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3444

    
3445
            if (targetLMConnector != null)
3446
            {
3447
                // LEADER Line 검사
3448
                bool leaderLine = false;
3449
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3450
                if (symbolMapping != null)
3451
                    leaderLine = symbolMapping.LEADERLINE;
3452

    
3453
                SegmentLocation location;
3454
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3455

    
3456
                Array array = null;
3457
                if (point != null)
3458
                    array = new double[] { 0, point[0], point[1] };
3459
                else
3460
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3461

    
3462
                LMLabelPersist _LmLabelPersist;
3463

    
3464
                Property property = endBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Freeze");
3465
                if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3466
                {
3467
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3468
                    if (_LmLabelPersist == null)
3469
                    {
3470
                        _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, IsLeaderVisible: leaderLine);
3471
                    }
3472
                }
3473
                else
3474
                {
3475
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3476
                    if (_LmLabelPersist == null)
3477
                    {
3478
                        _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, IsLeaderVisible: leaderLine);
3479
                    }
3480
                }
3481

    
3482
                if (_LmLabelPersist != null)
3483
                {
3484
                    _LmLabelPersist.Commit();
3485
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3486
                    if (_LmLabelPersist.ModelItemObject != null)
3487
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3488
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3489

    
3490
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3491

    
3492
                    // end break arrange
3493
                    if (property == null || string.IsNullOrEmpty(property.VALUE) || !property.VALUE.Equals("True"))
3494
                    {
3495
                        MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3496
                    }
3497

    
3498
                    ReleaseCOMObjects(_LmLabelPersist);
3499
                }
3500
                ReleaseCOMObjects(targetLMConnector);
3501
            }
3502
            else
3503
            {
3504
                Log.Write("End Break UID : " + endBreak.UID);
3505
                Log.Write("Can't find targetLMConnector");
3506
            }
3507
        }
3508

    
3509
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3510
        {
3511
            double x = 0, y = 0;
3512
            if (location.HasFlag(SegmentLocation.Up))
3513
                y = GridSetting.GetInstance().Length * 3;
3514
            else if (location.HasFlag(SegmentLocation.Down))
3515
                y = -GridSetting.GetInstance().Length * 3;
3516

    
3517
            if (location.HasFlag(SegmentLocation.Right))
3518
                x = GridSetting.GetInstance().Length * 3;
3519
            else if (location.HasFlag(SegmentLocation.Left))
3520
                x = -GridSetting.GetInstance().Length * 3;
3521

    
3522
            if (x != 0 || y != 0)
3523
            {
3524
                radApp.ActiveSelectSet.RemoveAll();
3525
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3526
                if (dependency != null)
3527
                {
3528
                    radApp.ActiveSelectSet.Add(dependency);
3529
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3530
                    transform.DefineByMove2d(x, y);
3531
                    radApp.ActiveSelectSet.Transform(transform, true);
3532
                    radApp.ActiveSelectSet.RemoveAll();
3533
                }
3534
            }
3535
        }
3536

    
3537
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3538
        {
3539
            string symbolPath = string.Empty;
3540
            #region get symbol path
3541
            if (string.IsNullOrEmpty(changeSymbolPath))
3542
            {
3543
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3544
                symbolPath = GetSPPIDFileName(modelItem);
3545
                ReleaseCOMObjects(modelItem);
3546
            }
3547
            else
3548
                symbolPath = changeSymbolPath;
3549

    
3550
            #endregion
3551

    
3552
            LMConnector newConnector = null;
3553
            dynamic OID = connector.get_GraphicOID().ToString();
3554
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3555
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3556
            int verticesCount = lineStringGeometry.VertexCount;
3557
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3558
            _LMAItem lMAItem = _placement.PIDCreateItem(symbolPath);
3559

    
3560
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3561
            {
3562
                double[] vertices = null;
3563
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3564
                double x = 0;
3565
                double y = 0;
3566
                lineStringGeometry.GetVertex(1, ref x, ref y);
3567

    
3568
                string flowDirection = string.Empty;
3569
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3570
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3571
                    flowDirection = flowAttribute.get_Value().ToString();
3572

    
3573
                if (flowDirection == "End 1 is downstream (Outlet)")
3574
                {
3575
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3576
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3577
                }
3578
                else
3579
                {
3580
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3581
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3582
                }
3583
                string oldModelItemId = connector.ModelItemID;
3584
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3585
                newConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3586
                newConnector.Commit();
3587
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3588
                SetFlowUpstream(newConnector.ModelItemID);
3589
                ReleaseCOMObjects(connector);
3590

    
3591
                SetFlowAllLine(oldModelItemId);
3592
            }
3593

    
3594
            return newConnector;
3595
        }
3596

    
3597
        /// <summary>
3598
        /// SpecBreak Modeling 메서드
3599
        /// </summary>
3600
        /// <param name="specBreak"></param>
3601
        private void SpecBreakModeling(SpecBreak specBreak)
3602
        {
3603
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3604
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3605

    
3606
            if (upStreamObj != null &&
3607
                downStreamObj != null)
3608
            {
3609
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3610
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) &&
3611
                    targetLMConnector != null &&
3612
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3613
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3614

    
3615
                if (targetLMConnector != null)
3616
                {
3617
                    foreach (var attribute in specBreak.ATTRIBUTES)
3618
                    {
3619
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3620
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3621
                        {
3622
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3623
                            SegmentLocation location;
3624
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3625
                            Array array = null;
3626
                            if (point != null)
3627
                                array = new double[] { 0, point[0], point[1] };
3628
                            else
3629
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3630
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3631

    
3632
                            if (_LmLabelPersist != null)
3633
                            {
3634
                                _LmLabelPersist.Commit();
3635
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3636
                                if (_LmLabelPersist.ModelItemObject != null)
3637
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3638
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3639

    
3640
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3641

    
3642
                                // spec break arrange
3643
                                MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3644

    
3645
                                ReleaseCOMObjects(_LmLabelPersist);
3646
                            }
3647
                        }
3648
                    }
3649

    
3650
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3651
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3652
                    {
3653
                        // temp
3654
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3655
                    }
3656
                    ReleaseCOMObjects(targetLMConnector);
3657
                }
3658
                else
3659
                {
3660
                    Log.Write("Spec Break UID : " + specBreak.UID);
3661
                    Log.Write("Can't find targetLMConnector");
3662
                }
3663
            }
3664
        }
3665

    
3666
        private bool IsRhombus(LMLabelPersist labelPersist, out double x, out double y, out double radius)
3667
        {
3668
            bool result = false;
3669
            x = 0; y = 0; radius = 0;
3670

    
3671
            string oid = labelPersist.get_GraphicOID().ToString();
3672
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3673

    
3674
            if (dependency != null)
3675
            {
3676
                bool isLabel = false;
3677
                foreach (var attributes in dependency.AttributeSets)
3678
                {
3679
                    foreach (var attribute in attributes)
3680
                    {
3681
                        string name = attribute.Name;
3682
                        string value = attribute.GetValue().ToString();
3683
                        if (name == "DrawingItemType" && value == "LabelPersist")
3684
                        {
3685
                            isLabel = true;
3686
                            break;
3687
                        }
3688
                    }
3689
                }
3690
                if (isLabel)
3691
                {
3692
                    double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
3693
                    foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
3694
                    {
3695
                        if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLine2d)
3696
                        {
3697
                            Ingr.RAD2D.Line2d line2D = drawingObject as Ingr.RAD2D.Line2d;
3698

    
3699
                            double x1, y1, x2, y2;
3700
                            line2D.GetStartPoint(out x1, out y1);
3701
                            line2D.GetEndPoint(out x2, out y2);
3702
                            double tX1 = Math.Min(x1, x2), tY1 = Math.Min(y1, y2), tX2 = Math.Max(x1, x2), tY2 = Math.Max(y1, y2);
3703
                            if (minX > tX1)
3704
                                minX = tX1;
3705
                            if (minY > tY1)
3706
                                minY = tY1;
3707
                            if (maxX < tX2)
3708
                                maxX = tX2;
3709
                            if (maxY < tY2)
3710
                                maxY = tY2;
3711
                        }
3712
                    }
3713

    
3714
                    double width = Math.Abs(maxX - minX);
3715
                    double height = Math.Abs(maxY - minY);
3716
                    double ratio = width / height * 100;
3717
                    if (ratio > 99d && ratio < 101d)
3718
                    {
3719
                        result = true;
3720
                    }
3721
                    x = (maxX + minX) / 2d;
3722
                    y = (maxY + minY) / 2d;
3723
                    radius = width / 2d;
3724
                }
3725
            }
3726

    
3727
            return result;
3728
        }
3729

    
3730
        private void MoveSegmentBreak(string connectorID, LMLabelPersist labelPersist)
3731
        {
3732
            bool bFind = false;
3733
            double x, y, radius;
3734
            if (IsRhombus(labelPersist, out x, out y, out radius))
3735
            {
3736
                List<double[]> itemPoints = new List<double[]>();
3737
                LMConnector connector = dataSource.GetConnector(connectorID);
3738
                foreach (LMLabelPersist label in connector.LabelPersists)
3739
                {
3740
                    if (!"Active".Equals(label.get_ItemStatus()))
3741
                        continue;
3742

    
3743
                    if (!label.Id.Equals(labelPersist.Id))
3744
                    {
3745
                        double centerX, centerY, temp;
3746
                        if (IsRhombus(label, out centerX, out centerY, out temp))
3747
                        {
3748
                            bFind = true;
3749
                            itemPoints.Add(new double[] { centerX, centerY });
3750
                        }
3751
                    }
3752
                }
3753
                ReleaseCOMObjects(connector);
3754

    
3755

    
3756
                if (bFind)
3757
                {
3758
                    double[] startPoint = itemPoints.First();
3759
                    itemPoints.RemoveAt(0);
3760

    
3761
                    for (int i = 0; i < 8; i++)
3762
                    {
3763
                        double pointX = 0, pointY = 0;
3764
                        switch (i)
3765
                        {
3766
                            case 0:
3767
                                pointX = startPoint[0] + radius;
3768
                                pointY = startPoint[1] + radius;
3769
                                break;
3770
                            case 1:
3771
                                pointX = startPoint[0] + radius + radius;
3772
                                pointY = startPoint[1];
3773
                                break;
3774
                            case 2:
3775
                                pointX = startPoint[0] + radius;
3776
                                pointY = startPoint[1] - radius;
3777
                                break;
3778
                            case 3:
3779
                                pointX = startPoint[0];
3780
                                pointY = startPoint[1] - radius - radius;
3781
                                break;
3782
                            case 4:
3783
                                pointX = startPoint[0] - radius;
3784
                                pointY = startPoint[1] - radius;
3785
                                break;
3786
                            case 5:
3787
                                pointX = startPoint[0] - radius - radius;
3788
                                pointY = startPoint[1];
3789
                                break;
3790
                            case 6:
3791
                                pointX = startPoint[0] - radius;
3792
                                pointY = startPoint[1] + radius;
3793
                                break;
3794
                            case 7:
3795
                                pointX = startPoint[0];
3796
                                pointY = startPoint[1] + radius + radius;
3797
                                break;
3798
                            default:
3799
                                break;
3800
                        }
3801

    
3802
                        if (!ExistSegmentByPoint(pointX, pointY))
3803
                        {
3804
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
3805
                            if (dependency != null)
3806
                            {
3807
                                radApp.ActiveSelectSet.RemoveAll();
3808
                                radApp.ActiveSelectSet.Add(dependency);
3809
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3810
                                transform.DefineByMove2d(pointX - x, pointY - y);
3811
                                radApp.ActiveSelectSet.Transform(transform, true);
3812
                                radApp.ActiveSelectSet.RemoveAll();
3813
                            }
3814
                            break;
3815
                        }
3816
                    }
3817

    
3818
                    bool ExistSegmentByPoint(double pointX, double pointY)
3819
                    {
3820
                        bool result = false;
3821
                        foreach (var item in itemPoints)
3822
                        {
3823
                            double distance = SPPIDUtil.CalcPointToPointdDistance(item[0], item[1], pointX, pointY);
3824
                            if (Math.Truncate(distance * 1000000000d).Equals(0))
3825
                                result = true;
3826
                        }
3827
                        return result;
3828
                    }
3829
                }
3830
            }
3831

    
3832
            if (!bFind)
3833
                MoveSegmentBestLocation(labelPersist.get_GraphicOID().ToString(), new double[] { x - radius, y - radius, x + radius, y + radius }, itemRange);
3834
        }
3835

    
3836
        LMConnectors GetConnectors()
3837
        {
3838
            LMAFilter filter = new LMAFilter();
3839
            LMACriterion criterion1 = new LMACriterion();
3840
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3841
            criterion1.Operator = "=";
3842
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3843
            criterion1.Conjunctive = true;
3844
            filter.get_Criteria().Add(criterion1);
3845
            filter.ItemType = "Connector";
3846

    
3847
            LMACriterion criterion2 = new LMACriterion();
3848
            criterion2.SourceAttributeName = "ITEMSTATUS";
3849
            criterion2.Operator = "=";
3850
            criterion2.set_ValueAttribute("1");
3851
            criterion2.Conjunctive = true;
3852
            filter.get_Criteria().Add(criterion2);
3853

    
3854
            LMACriterion criterion3 = new LMACriterion();
3855
            criterion3.SourceAttributeName = "INSTOCKPILE";
3856
            criterion3.Operator = "=";
3857
            criterion3.set_ValueAttribute("1");
3858
            criterion3.Conjunctive = true;
3859
            filter.get_Criteria().Add(criterion3);
3860

    
3861
            LMConnectors items = new LMConnectors();
3862
            items.Collect(dataSource, Filter: filter);
3863

    
3864
            ReleaseCOMObjects(filter);
3865
            ReleaseCOMObjects(criterion1);
3866
            ReleaseCOMObjects(criterion2);
3867
            ReleaseCOMObjects(criterion3);
3868

    
3869
            return items;
3870
        }
3871
        LMSymbols GetSymbols()
3872
        {
3873
            LMAFilter filter = new LMAFilter();
3874
            LMACriterion criterion1 = new LMACriterion();
3875
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3876
            criterion1.Operator = "=";
3877
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3878
            criterion1.Conjunctive = true;
3879
            filter.get_Criteria().Add(criterion1);
3880
            filter.ItemType = "Symbol";
3881

    
3882
            LMACriterion criterion2 = new LMACriterion();
3883
            criterion2.SourceAttributeName = "ITEMSTATUS";
3884
            criterion2.Operator = "=";
3885
            criterion2.set_ValueAttribute("1");
3886
            criterion2.Conjunctive = true;
3887
            filter.get_Criteria().Add(criterion2);
3888

    
3889
            LMACriterion criterion3 = new LMACriterion();
3890
            criterion3.SourceAttributeName = "INSTOCKPILE";
3891
            criterion3.Operator = "=";
3892
            criterion3.set_ValueAttribute("1");
3893
            criterion3.Conjunctive = true;
3894
            filter.get_Criteria().Add(criterion3);
3895

    
3896
            LMSymbols items = new LMSymbols();
3897
            items.Collect(dataSource, Filter: filter);
3898

    
3899
            ReleaseCOMObjects(filter);
3900
            ReleaseCOMObjects(criterion1);
3901
            ReleaseCOMObjects(criterion2);
3902
            ReleaseCOMObjects(criterion3);
3903

    
3904
            return items;
3905
        }
3906

    
3907
        private void SetConnectorAndSymbolRange()
3908
        {
3909
            itemRange = new List<double[]>();
3910

    
3911
            LMConnectors connectors = GetConnectors();
3912
            foreach (LMConnector connector in connectors)
3913
            {
3914
                List<double[]> vertices = GetConnectorVertices(connector);
3915
                for (int i = 0; i < vertices.Count - 1; i++)
3916
                {
3917
                    double[] point1 = vertices[i];
3918
                    double[] point2 = vertices[i + 1];
3919
                    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]);
3920
                    double gap = 0.0001d;
3921
                    itemRange.Add(new double[] { x1 - gap, y1 - gap, x2 + gap, y2 + gap });
3922
                }
3923
                ReleaseCOMObjects(connector);
3924
            }
3925
            ReleaseCOMObjects(connectors);
3926

    
3927
            LMSymbols symbols = GetSymbols();
3928
            foreach (LMSymbol symbol in symbols)
3929
            {
3930
                string oid = symbol.get_GraphicOID().ToString();
3931
                DrawingObjectBase drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid];
3932
                if (drawingObject != null)
3933
                {
3934
                    double x1, y1, x2, y2;
3935
                    drawingObject.Range(out x1, out y1, out x2, out y2);
3936
                    itemRange.Add(new double[] { x1, y1, x2, y2 });
3937
                }
3938

    
3939
                ReleaseCOMObjects(symbol);
3940
            }
3941
            ReleaseCOMObjects(symbols);
3942
        }
3943

    
3944
        private void MoveSegmentBestLocation(string oid, double[] segmentRange, List<double[]> allRanges)
3945
        {
3946
            double minValue = Math.Min(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3947
            double maxValue = Math.Max(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3948

    
3949
            double maxX = 0, maxY = 0;
3950
            maxX = maxValue * 10;
3951
            maxY = minValue * 10;
3952

    
3953
            double move = minValue / 10d;
3954
            double textGap = minValue / 3d;
3955
            segmentRange = new double[] { segmentRange[0] - textGap, segmentRange[1] - textGap, segmentRange[2] + textGap, segmentRange[3] + textGap };
3956

    
3957

    
3958
            List<double[]> containRanges = new List<double[]>();
3959
            double[] findRange = new double[] {
3960
            segmentRange[0] - maxX, segmentRange[1] - maxY,
3961
            segmentRange[2] + maxX, segmentRange[3] + maxY};
3962

    
3963
            foreach (var range in allRanges)
3964
                if (SPPIDUtil.IsOverlap(findRange, range))
3965
                    containRanges.Add(range);
3966

    
3967
            double movePointX = 0, movePointY = 0, distance = double.MaxValue;
3968
            for (double x = 0; x < maxX; x = x + move)
3969
                for (double y = 0; y < maxY; y = y + move)
3970
                    for (int i = 0; i < 4; i++)
3971
                    {
3972
                        double tempX = 0d, tempY = 0d;
3973
                        switch (i)
3974
                        {
3975
                            case 0:
3976
                                tempX = x;
3977
                                tempY = y;
3978
                                break;
3979
                            case 1:
3980
                                tempX = -x;
3981
                                tempY = y;
3982
                                break;
3983
                            case 2:
3984
                                tempX = -x;
3985
                                tempY = -y;
3986
                                break;
3987
                            case 3:
3988
                                tempX = x;
3989
                                tempY = -y;
3990
                                break;
3991
                            default:
3992
                                break;
3993
                        }
3994

    
3995
                        bool result = true;
3996
                        double[] movedRange = new double[] { segmentRange[0] + tempX, segmentRange[1] + tempY, segmentRange[2] + tempX, segmentRange[3] + tempY };
3997
                        foreach (double[] range in containRanges)
3998
                        {
3999
                            if (SPPIDUtil.IsOverlap(range, movedRange))
4000
                            {
4001
                                result = false;
4002
                                break;
4003
                            }
4004
                        }
4005

    
4006
                        if (result)
4007
                        {
4008
                            //double tempDistance = Utils.CalcDistance(new double[] { 0, 0, 0 }, new double[] { tempX, tempY, 0 });
4009
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(0, 0, tempX, tempY);
4010
                            bool bChange = false;
4011
                            if (distance > tempDistance)
4012
                                bChange = true;
4013
                            else if (distance.Equals(tempDistance) && (movePointX.Equals(0d) || movePointY.Equals(0d)))
4014
                                bChange = true;
4015

    
4016
                            if (bChange)
4017
                            {
4018
                                distance = tempDistance;
4019
                                movePointX = tempX;
4020
                                movePointY = tempY;
4021
                            }
4022
                        }
4023
                    }
4024

    
4025
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
4026
            if (dependency != null)
4027
            {
4028
                radApp.ActiveSelectSet.RemoveAll();
4029
                radApp.ActiveSelectSet.Add(dependency);
4030
                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4031
                transform.DefineByMove2d(movePointX, movePointY);
4032
                radApp.ActiveSelectSet.Transform(transform, true);
4033
                radApp.ActiveSelectSet.RemoveAll();
4034
            }
4035
        }
4036

    
4037
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
4038
        {
4039
            LMConnector targetConnector = null;
4040
            Symbol targetSymbol = targetObj as Symbol;
4041
            Symbol connectedSymbol = connectedObj as Symbol;
4042
            Line targetLine = targetObj as Line;
4043
            Line connectedLine = connectedObj as Line;
4044
            if (targetSymbol != null && connectedSymbol != null)
4045
            {
4046
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4047
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4048

    
4049
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
4050
                {
4051
                    if (connector.get_ItemStatus() != "Active")
4052
                        continue;
4053

    
4054
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
4055
                    {
4056
                        targetConnector = connector;
4057
                        break;
4058
                    }
4059
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
4060
                    {
4061
                        targetConnector = connector;
4062
                        break;
4063
                    }
4064
                }
4065

    
4066
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
4067
                {
4068
                    if (connector.get_ItemStatus() != "Active")
4069
                        continue;
4070

    
4071
                    if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
4072
                    {
4073
                        targetConnector = connector;
4074
                        break;
4075
                    }
4076
                    else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
4077
                    {
4078
                        targetConnector = connector;
4079
                        break;
4080
                    }
4081
                }
4082

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

    
4091
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
4092
                {
4093
                    foreach (LMRepresentation rep in targetModelItem.Representations)
4094
                    {
4095
                        if (targetConnector != null)
4096
                            break;
4097

    
4098
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4099
                        {
4100
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4101

    
4102
                            if (IsConnected(_LMConnector, connectedModelItem))
4103
                                targetConnector = _LMConnector;
4104
                            else
4105
                                ReleaseCOMObjects(_LMConnector);
4106
                        }
4107
                    }
4108

    
4109
                    ReleaseCOMObjects(targetModelItem);
4110
                }
4111
            }
4112
            else
4113
            {
4114
                LMSymbol connectedLMSymbol = null;
4115
                if (connectedSymbol != null)
4116
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4117
                else if (targetSymbol != null)
4118
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4119
                else
4120
                {
4121

    
4122
                }
4123
                LMModelItem targetModelItem = null;
4124
                if (targetLine != null)
4125
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4126
                else if (connectedLine != null)
4127
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4128
                else
4129
                {
4130

    
4131
                }
4132
                if (connectedLMSymbol != null && targetModelItem != null)
4133
                {
4134
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
4135
                    {
4136
                        if (connector.get_ItemStatus() != "Active")
4137
                            continue;
4138

    
4139
                        if (IsConnected(connector, targetModelItem))
4140
                        {
4141
                            targetConnector = connector;
4142
                            break;
4143
                        }
4144
                    }
4145

    
4146
                    if (targetConnector == null)
4147
                    {
4148
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
4149
                        {
4150
                            if (connector.get_ItemStatus() != "Active")
4151
                                continue;
4152

    
4153
                            if (IsConnected(connector, targetModelItem))
4154
                            {
4155
                                targetConnector = connector;
4156
                                break;
4157
                            }
4158
                        }
4159
                    }
4160
                }
4161

    
4162
            }
4163

    
4164
            return targetConnector;
4165
        }
4166

    
4167
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
4168
        {
4169
            double[] result = null;
4170
            Line targetLine = targetObj as Line;
4171
            Symbol targetSymbol = targetObj as Symbol;
4172
            Line connLine = connObj as Line;
4173
            Symbol connSymbol = connObj as Symbol;
4174
            location = SegmentLocation.None;
4175
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
4176
            {
4177
                result = GetConnectorVertices(targetConnector)[0];
4178
                if (targetSymbol != null && connSymbol != null)
4179
                {
4180
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
4181
                    result = new double[] { result[0], result[1] };
4182
                    if (slopeType == SlopeType.HORIZONTAL)
4183
                        location = SegmentLocation.Up;
4184
                    else if (slopeType == SlopeType.VERTICAL)
4185
                        location = SegmentLocation.Right;
4186
                }
4187
                else if (targetLine != null)
4188
                {
4189
                    result = new double[] { result[0], result[1] };
4190
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4191
                        location = SegmentLocation.Up;
4192
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
4193
                        location = SegmentLocation.Right;
4194
                }
4195
                else if (connLine != null)
4196
                {
4197
                    result = new double[] { result[0], result[1] };
4198
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
4199
                        location = SegmentLocation.Up;
4200
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
4201
                        location = SegmentLocation.Right;
4202
                }
4203
            }
4204
            else
4205
            {
4206
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
4207
                {
4208
                    Line line = connObj as Line;
4209
                    LMConnector connectedConnector = null;
4210
                    int connIndex = 0;
4211
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4212
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
4213

    
4214
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
4215

    
4216
                    ReleaseCOMObjects(modelItem);
4217
                    ReleaseCOMObjects(connectedConnector);
4218

    
4219
                    if (vertices.Count > 0)
4220
                    {
4221
                        if (connIndex == 1)
4222
                            result = vertices[0];
4223
                        else if (connIndex == 2)
4224
                            result = vertices[vertices.Count - 1];
4225

    
4226
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4227
                        {
4228
                            result = new double[] { result[0], result[1] };
4229
                            location = SegmentLocation.Up;
4230
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4231
                                location = location | SegmentLocation.Right;
4232
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4233
                                location = location | SegmentLocation.Left;
4234
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4235
                                location = location | SegmentLocation.Left;
4236
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4237
                                location = location | SegmentLocation.Right;
4238
                        }
4239
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
4240
                        {
4241
                            result = new double[] { result[0], result[1] };
4242
                            location = SegmentLocation.Right;
4243
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4244
                                location = location | SegmentLocation.Up;
4245
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4246
                                location = location | SegmentLocation.Down;
4247
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4248
                                location = location | SegmentLocation.Down;
4249
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4250
                                location = location | SegmentLocation.Up;
4251
                        }
4252

    
4253
                    }
4254
                }
4255
                else
4256
                {
4257
                    Log.Write("error in GetSegemtPoint");
4258
                }
4259
            }
4260

    
4261
            return result;
4262
        }
4263

    
4264
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
4265
        {
4266
            bool result = false;
4267

    
4268
            foreach (LMRepresentation rep in modelItem.Representations)
4269
            {
4270
                if (result)
4271
                    break;
4272

    
4273
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4274
                {
4275
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4276

    
4277
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4278
                        connector.ConnectItem1SymbolObject != null &&
4279
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4280
                    {
4281
                        result = true;
4282
                        ReleaseCOMObjects(_LMConnector);
4283
                        break;
4284
                    }
4285
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4286
                        connector.ConnectItem2SymbolObject != null &&
4287
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4288
                    {
4289
                        result = true;
4290
                        ReleaseCOMObjects(_LMConnector);
4291
                        break;
4292
                    }
4293
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4294
                        connector.ConnectItem1SymbolObject != null &&
4295
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4296
                    {
4297
                        result = true;
4298
                        ReleaseCOMObjects(_LMConnector);
4299
                        break;
4300
                    }
4301
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4302
                        connector.ConnectItem2SymbolObject != null &&
4303
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4304
                    {
4305
                        result = true;
4306
                        ReleaseCOMObjects(_LMConnector);
4307
                        break;
4308
                    }
4309

    
4310
                    ReleaseCOMObjects(_LMConnector);
4311
                }
4312
            }
4313

    
4314

    
4315
            return result;
4316
        }
4317

    
4318
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
4319
        {
4320
            foreach (LMRepresentation rep in modelItem.Representations)
4321
            {
4322
                if (connectedConnector != null)
4323
                    break;
4324

    
4325
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4326
                {
4327
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4328

    
4329
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4330
                        connector.ConnectItem1SymbolObject != null &&
4331
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4332
                    {
4333
                        connectedConnector = _LMConnector;
4334
                        connectorIndex = 1;
4335
                        break;
4336
                    }
4337
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4338
                        connector.ConnectItem2SymbolObject != null &&
4339
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4340
                    {
4341
                        connectedConnector = _LMConnector;
4342
                        connectorIndex = 2;
4343
                        break;
4344
                    }
4345
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4346
                        connector.ConnectItem1SymbolObject != null &&
4347
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4348
                    {
4349
                        connectedConnector = _LMConnector;
4350
                        connectorIndex = 1;
4351
                        break;
4352
                    }
4353
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4354
                        connector.ConnectItem2SymbolObject != null &&
4355
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4356
                    {
4357
                        connectedConnector = _LMConnector;
4358
                        connectorIndex = 2;
4359
                        break;
4360
                    }
4361

    
4362
                    if (connectedConnector == null)
4363
                        ReleaseCOMObjects(_LMConnector);
4364
                }
4365
            }
4366
        }
4367

    
4368
        /// <summary>
4369
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
4370
        /// </summary>
4371
        /// <param name="modelItemID1"></param>
4372
        /// <param name="modelItemID2"></param>
4373
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
4374
        {
4375
            try
4376
            {
4377
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
4378
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
4379
                List<double[]> vertices1 = null;
4380
                string graphicOID1 = string.Empty;
4381
                if (connector1 != null)
4382
                {
4383
                    vertices1 = GetConnectorVertices(connector1);
4384
                    graphicOID1 = connector1.get_GraphicOID();
4385
                }
4386
                _LMAItem item1 = modelItem1.AsLMAItem();
4387
                ReleaseCOMObjects(connector1);
4388
                connector1 = null;
4389

    
4390
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
4391
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
4392
                List<double[]> vertices2 = null;
4393
                string graphicOID2 = string.Empty;
4394
                if (connector2 != null)
4395
                {
4396
                    vertices2 = GetConnectorVertices(connector2);
4397
                    graphicOID2 = connector2.get_GraphicOID();
4398
                }
4399
                _LMAItem item2 = modelItem2.AsLMAItem();
4400
                ReleaseCOMObjects(connector2);
4401
                connector2 = null;
4402

    
4403

    
4404
                ISPClientData3.ISPItem ispItem1 = item1.ISPItem;
4405
                ISPClientData3.ISPItemType ispItemType1 = ispItem1.get_ItemType();
4406
                foreach (ISPClientData3.ISPAttribute attrib in ispItem1.get_Attributes())
4407
                {
4408
                    if (attrib.AttName == "PipeRunType")
4409
                    {
4410
                        string aa = attrib.Value;
4411
                    }
4412
                }
4413

    
4414

    
4415
                ISPClientData3.ISPItem ispItem2 = item2.ISPItem;
4416
                ISPClientData3.ISPItemType ispItemType2 = ispItem2.get_ItemType();
4417
                foreach (ISPClientData3.ISPAttribute attrib in ispItem2.get_Attributes())
4418
                {
4419
                    if (attrib.AttName == "PipeRunType")
4420
                    {
4421
                        string aa = attrib.Value;
4422
                    }
4423
                }
4424

    
4425

    
4426
                // item2가 item1으로 조인
4427
                _placement.PIDJoinRuns(ref item1, ref item2);
4428
                item1.Commit();
4429
                item2.Commit();
4430

    
4431
                string beforeID = string.Empty;
4432
                string afterID = string.Empty;
4433

    
4434
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
4435
                {
4436
                    beforeID = modelItem2.Id;
4437
                    afterID = modelItem1.Id;
4438
                    survivorId = afterID;
4439
                }
4440
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
4441
                {
4442
                    beforeID = modelItem1.Id;
4443
                    afterID = modelItem2.Id;
4444
                    survivorId = afterID;
4445
                }
4446
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
4447
                {
4448
                    int model1Cnt = GetConnectorCount(modelId1);
4449
                    int model2Cnt = GetConnectorCount(modelId2);
4450
                    if (model1Cnt == 0)
4451
                    {
4452
                        beforeID = modelItem1.Id;
4453
                        afterID = modelItem2.Id;
4454
                        survivorId = afterID;
4455
                    }
4456
                    else if (model2Cnt == 0)
4457
                    {
4458
                        beforeID = modelItem2.Id;
4459
                        afterID = modelItem1.Id;
4460
                        survivorId = afterID;
4461
                    }
4462
                    else
4463
                        survivorId = null;
4464
                }
4465
                else
4466
                {
4467
                    Log.Write("잘못된 경우");
4468
                    survivorId = null;
4469
                }
4470

    
4471
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
4472
                {
4473
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
4474
                    foreach (var line in lines)
4475
                        line.SPPID.ModelItemId = afterID;
4476
                }
4477

    
4478
                ReleaseCOMObjects(modelItem1);
4479
                ReleaseCOMObjects(item1);
4480
                ReleaseCOMObjects(modelItem2);
4481
                ReleaseCOMObjects(item2);
4482
            }
4483
            catch (Exception ex)
4484
            {
4485
                Log.Write("Join Error");
4486
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
4487
            }
4488
        }
4489
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
4490
        {
4491
            bool result = false;
4492
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
4493
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
4494
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
4495

    
4496
            foreach (var item in endBreaks)
4497
            {
4498
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
4499
                {
4500
                    result = true;
4501
                    break;
4502
                }
4503
            }
4504

    
4505
            return result;
4506
        }
4507
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
4508
        {
4509
            List<string> temp = new List<string>();
4510
            List<LMConnector> connectors = new List<LMConnector>();
4511
            foreach (LMConnector connector in symbol.Avoid1Connectors)
4512
            {
4513
                if (connector.get_ItemStatus() != "Active")
4514
                    continue;
4515

    
4516
                LMModelItem modelItem = connector.ModelItemObject;
4517
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4518
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4519
                    temp.Add(modelItem.Id);
4520

    
4521
                if (temp.Contains(modelItem.Id) &&
4522
                    connOtherSymbol != null &&
4523
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4524
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4525
                    temp.Remove(modelItem.Id);
4526

    
4527

    
4528
                if (temp.Contains(modelItem.Id))
4529
                    connectors.Add(connector);
4530
                ReleaseCOMObjects(connOtherSymbol);
4531
                connOtherSymbol = null;
4532
                ReleaseCOMObjects(modelItem);
4533
                modelItem = null;
4534
            }
4535

    
4536
            foreach (LMConnector connector in symbol.Avoid2Connectors)
4537
            {
4538
                if (connector.get_ItemStatus() != "Active")
4539
                    continue;
4540

    
4541
                LMModelItem modelItem = connector.ModelItemObject;
4542
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4543
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4544
                    temp.Add(modelItem.Id);
4545

    
4546
                if (temp.Contains(modelItem.Id) &&
4547
                    connOtherSymbol != null &&
4548
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4549
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4550
                    temp.Remove(modelItem.Id);
4551

    
4552
                if (temp.Contains(modelItem.Id))
4553
                    connectors.Add(connector);
4554
                ReleaseCOMObjects(connOtherSymbol);
4555
                connOtherSymbol = null;
4556
                ReleaseCOMObjects(modelItem);
4557
                modelItem = null;
4558
            }
4559

    
4560

    
4561
            List<string> result = new List<string>();
4562
            string originalName = GetSPPIDFileName(modelId);
4563
            foreach (var connector in connectors)
4564
            {
4565
                string fileName = GetSPPIDFileName(connector.ModelItemID);
4566
                if (originalName == fileName)
4567
                    result.Add(connector.ModelItemID);
4568
                else
4569
                {
4570
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
4571
                        result.Add(connector.ModelItemID);
4572
                    else
4573
                    {
4574
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
4575
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
4576
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
4577
                            result.Add(connector.ModelItemID);
4578
                    }
4579
                }
4580
            }
4581

    
4582
            foreach (var connector in connectors)
4583
                ReleaseCOMObjects(connector);
4584

    
4585
            return result;
4586

    
4587

    
4588
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
4589
            {
4590
                LMSymbol findResult = null;
4591
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
4592
                    findResult = connector.ConnectItem1SymbolObject;
4593
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
4594
                    findResult = connector.ConnectItem2SymbolObject;
4595

    
4596
                return findResult;
4597
            }
4598
        }
4599

    
4600
        /// <summary>
4601
        /// PipeRun의 좌표를 가져오는 메서드
4602
        /// </summary>
4603
        /// <param name="modelId"></param>
4604
        /// <returns></returns>
4605
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
4606
        {
4607
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
4608
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
4609

    
4610
            if (modelItem != null)
4611
            {
4612
                foreach (LMRepresentation rep in modelItem.Representations)
4613
                {
4614
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4615
                    {
4616
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4617
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
4618
                        {
4619
                            ReleaseCOMObjects(_LMConnector);
4620
                            _LMConnector = null;
4621
                            continue;
4622
                        }
4623
                        connectorVertices.Add(_LMConnector, new List<double[]>());
4624
                        dynamic OID = rep.get_GraphicOID().ToString();
4625
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4626
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4627
                        int verticesCount = lineStringGeometry.VertexCount;
4628
                        double[] vertices = null;
4629
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
4630
                        for (int i = 0; i < verticesCount; i++)
4631
                        {
4632
                            double x = 0;
4633
                            double y = 0;
4634
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4635
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
4636
                        }
4637
                    }
4638
                }
4639

    
4640
                ReleaseCOMObjects(modelItem);
4641
            }
4642

    
4643
            return connectorVertices;
4644
        }
4645

    
4646
        private List<double[]> GetConnectorVertices(LMConnector connector)
4647
        {
4648
            List<double[]> vertices = new List<double[]>();
4649
            if (connector != null)
4650
            {
4651
                dynamic OID = connector.get_GraphicOID().ToString();
4652
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4653
                if (drawingObject != null)
4654
                {
4655
                    Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4656
                    int verticesCount = lineStringGeometry.VertexCount;
4657
                    double[] value = null;
4658
                    lineStringGeometry.GetVertices(ref verticesCount, ref value);
4659
                    for (int i = 0; i < verticesCount; i++)
4660
                    {
4661
                        double x = 0;
4662
                        double y = 0;
4663
                        lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4664
                        vertices.Add(new double[] { x, y });
4665
                    }
4666
                }
4667
            }
4668
            return vertices;
4669
        }
4670

    
4671
        private double GetConnectorDistance(LMConnector connector)
4672
        {
4673
            double result = 0;
4674
            List<double[]> vertices = new List<double[]>();
4675
            if (connector != null)
4676
            {
4677
                dynamic OID = connector.get_GraphicOID().ToString();
4678
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4679
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4680
                int verticesCount = lineStringGeometry.VertexCount;
4681
                double[] value = null;
4682
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4683
                for (int i = 0; i < verticesCount; i++)
4684
                {
4685
                    double x = 0;
4686
                    double y = 0;
4687
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4688
                    vertices.Add(new double[] { x, y });
4689
                    if (vertices.Count > 1)
4690
                    {
4691
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
4692
                    }
4693
                }
4694
            }
4695
            return result;
4696
        }
4697
        private double[] GetConnectorRange(LMConnector connector)
4698
        {
4699
            double[] result = null;
4700
            List<double[]> vertices = new List<double[]>();
4701
            if (connector != null)
4702
            {
4703
                dynamic OID = connector.get_GraphicOID().ToString();
4704
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4705
                double minX = 0;
4706
                double minY = 0;
4707
                double maxX = 0;
4708
                double maxY = 0;
4709

    
4710
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
4711
                result = new double[] { minX, minY, maxX, maxY };
4712
            }
4713
            return result;
4714
        }
4715
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
4716
        {
4717
            List<double[]> vertices = null;
4718
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
4719
            if (drawingObject != null)
4720
            {
4721
                vertices = new List<double[]>();
4722
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4723
                int verticesCount = lineStringGeometry.VertexCount;
4724
                double[] value = null;
4725
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4726
                for (int i = 0; i < verticesCount; i++)
4727
                {
4728
                    double x = 0;
4729
                    double y = 0;
4730
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4731
                    vertices.Add(new double[] { x, y });
4732
                }
4733
            }
4734
            return vertices;
4735
        }
4736
        /// <summary>
4737
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
4738
        /// </summary>
4739
        /// <param name="connectorVertices"></param>
4740
        /// <param name="connX"></param>
4741
        /// <param name="connY"></param>
4742
        /// <returns></returns>
4743
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
4744
        {
4745
            double length = double.MaxValue;
4746
            LMConnector targetConnector = null;
4747
            foreach (var item in connectorVertices)
4748
            {
4749
                List<double[]> points = item.Value;
4750
                for (int i = 0; i < points.Count - 1; i++)
4751
                {
4752
                    double[] point1 = points[i];
4753
                    double[] point2 = points[i + 1];
4754
                    double x1 = Math.Min(point1[0], point2[0]);
4755
                    double y1 = Math.Min(point1[1], point2[1]);
4756
                    double x2 = Math.Max(point1[0], point2[0]);
4757
                    double y2 = Math.Max(point1[1], point2[1]);
4758

    
4759
                    if ((x1 <= connX && x2 >= connX) ||
4760
                        (y1 <= connY && y2 >= connY))
4761
                    {
4762
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
4763
                        if (length >= distance)
4764
                        {
4765
                            targetConnector = item.Key;
4766
                            length = distance;
4767
                        }
4768

    
4769
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
4770
                        if (length >= distance)
4771
                        {
4772
                            targetConnector = item.Key;
4773
                            length = distance;
4774
                        }
4775
                    }
4776
                }
4777
            }
4778

    
4779
            // 못찾았을때.
4780
            length = double.MaxValue;
4781
            if (targetConnector == null)
4782
            {
4783
                foreach (var item in connectorVertices)
4784
                {
4785
                    List<double[]> points = item.Value;
4786

    
4787
                    foreach (double[] point in points)
4788
                    {
4789
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
4790
                        if (length >= distance)
4791
                        {
4792
                            targetConnector = item.Key;
4793
                            length = distance;
4794
                        }
4795
                    }
4796
                }
4797
            }
4798

    
4799
            return targetConnector;
4800
        }
4801

    
4802
        private LMConnector FindTargetLMConnectorForBranch(Line currentLine, Line targetLine, ref double x, ref double y)
4803
        {
4804
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4805
            if (vertices.Count == 0)
4806
                return null;
4807

    
4808
            double length = double.MaxValue;
4809
            LMConnector targetConnector = null;
4810
            double[] resultPoint = null;
4811
            List<double[]> targetVertices = null;
4812

    
4813
            // Vertices 포인트에 제일 가까운곳
4814
            foreach (var item in vertices)
4815
            {
4816
                List<double[]> points = item.Value;
4817
                for (int i = 0; i < points.Count; i++)
4818
                {
4819
                    double[] point = points[i];
4820
                    double tempX = point[0];
4821
                    double tempY = point[1];
4822

    
4823
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4824
                    if (length >= distance)
4825
                    {
4826
                        targetConnector = item.Key;
4827
                        length = distance;
4828
                        resultPoint = point;
4829
                        targetVertices = item.Value;
4830
                    }
4831
                }
4832
            }
4833

    
4834
            // Vertices Cross에 제일 가까운곳
4835
            foreach (var item in vertices)
4836
            {
4837
                List<double[]> points = item.Value;
4838
                for (int i = 0; i < points.Count - 1; i++)
4839
                {
4840
                    double[] point1 = points[i];
4841
                    double[] point2 = points[i + 1];
4842

    
4843
                    double maxLineX = Math.Max(point1[0], point2[0]);
4844
                    double minLineX = Math.Min(point1[0], point2[0]);
4845
                    double maxLineY = Math.Max(point1[1], point2[1]);
4846
                    double minLineY = Math.Min(point1[1], point2[1]);
4847

    
4848
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4849

    
4850
                    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]);
4851
                    if (crossingPoint != null)
4852
                    {
4853
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4854
                        if (length >= distance)
4855
                        {
4856
                            if (slope == SlopeType.Slope &&
4857
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4858
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4859
                            {
4860
                                targetConnector = item.Key;
4861
                                length = distance;
4862
                                resultPoint = crossingPoint;
4863
                                targetVertices = item.Value;
4864
                            }
4865
                            else if (slope == SlopeType.HORIZONTAL &&
4866
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4867
                            {
4868
                                targetConnector = item.Key;
4869
                                length = distance;
4870
                                resultPoint = crossingPoint;
4871
                                targetVertices = item.Value;
4872
                            }
4873
                            else if (slope == SlopeType.VERTICAL &&
4874
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4875
                            {
4876
                                targetConnector = item.Key;
4877
                                length = distance;
4878
                                resultPoint = crossingPoint;
4879
                                targetVertices = item.Value;
4880
                            }
4881
                        }
4882
                    }
4883
                }
4884
            }
4885

    
4886
            foreach (var item in vertices)
4887
                if (item.Key != null && item.Key != targetConnector)
4888
                    ReleaseCOMObjects(item.Key);
4889

    
4890
            if (SPPIDUtil.IsBranchLine(currentLine, targetLine))
4891
            {
4892
                double tempResultX = resultPoint[0];
4893
                double tempResultY = resultPoint[1];
4894
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4895

    
4896
                GridSetting gridSetting = GridSetting.GetInstance();
4897
                for (int i = 0; i < targetVertices.Count; i++)
4898
                {
4899
                    double[] point = targetVertices[i];
4900
                    double tempX = targetVertices[i][0];
4901
                    double tempY = targetVertices[i][1];
4902
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4903
                    if (tempX == tempResultX && tempY == tempResultY)
4904
                    {
4905
                        if (i == 0)
4906
                        {
4907
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4908
                            bool containZeroLength = false;
4909
                            if (connSymbol != null)
4910
                            {
4911
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4912
                                {
4913
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4914
                                        containZeroLength = true;
4915
                                }
4916
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4917
                                {
4918
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4919
                                        containZeroLength = true;
4920
                                }
4921
                            }
4922

    
4923
                            if (connSymbol == null ||
4924
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4925
                                containZeroLength)
4926
                            {
4927
                                bool bCalcX = false;
4928
                                bool bCalcY = false;
4929
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4930
                                    bCalcX = true;
4931
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4932
                                    bCalcY = true;
4933
                                else
4934
                                {
4935
                                    bCalcX = true;
4936
                                    bCalcY = true;
4937
                                }
4938

    
4939
                                if (bCalcX)
4940
                                {
4941
                                    double nextX = targetVertices[i + 1][0];
4942
                                    double newX = 0;
4943
                                    if (nextX > tempX)
4944
                                    {
4945
                                        newX = tempX + gridSetting.Length;
4946
                                        if (newX > nextX)
4947
                                            newX = (point[0] + nextX) / 2;
4948
                                    }
4949
                                    else
4950
                                    {
4951
                                        newX = tempX - gridSetting.Length;
4952
                                        if (newX < nextX)
4953
                                            newX = (point[0] + nextX) / 2;
4954
                                    }
4955
                                    resultPoint = new double[] { newX, resultPoint[1] };
4956
                                }
4957

    
4958
                                if (bCalcY)
4959
                                {
4960
                                    double nextY = targetVertices[i + 1][1];
4961
                                    double newY = 0;
4962
                                    if (nextY > tempY)
4963
                                    {
4964
                                        newY = tempY + gridSetting.Length;
4965
                                        if (newY > nextY)
4966
                                            newY = (point[1] + nextY) / 2;
4967
                                    }
4968
                                    else
4969
                                    {
4970
                                        newY = tempY - gridSetting.Length;
4971
                                        if (newY < nextY)
4972
                                            newY = (point[1] + nextY) / 2;
4973
                                    }
4974
                                    resultPoint = new double[] { resultPoint[0], newY };
4975
                                }
4976
                            }
4977
                        }
4978
                        else if (i == targetVertices.Count - 1 && targetVertices.Count != 2)
4979
                        {
4980
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4981
                            bool containZeroLength = false;
4982
                            if (connSymbol != null)
4983
                            {
4984
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4985
                                {
4986
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4987
                                        containZeroLength = true;
4988
                                }
4989
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4990
                                {
4991
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4992
                                        containZeroLength = true;
4993
                                }
4994
                            }
4995

    
4996
                            if (connSymbol == null ||
4997
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4998
                                containZeroLength)
4999
                            {
5000
                                bool bCalcX = false;
5001
                                bool bCalcY = false;
5002
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
5003
                                    bCalcX = true;
5004
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
5005
                                    bCalcY = true;
5006
                                else
5007
                                {
5008
                                    bCalcX = true;
5009
                                    bCalcY = true;
5010
                                }
5011

    
5012
                                if (bCalcX)
5013
                                {
5014
                                    double nextX = targetVertices[i - 1][0];
5015
                                    double newX = 0;
5016
                                    if (nextX > tempX)
5017
                                    {
5018
                                        newX = tempX + gridSetting.Length;
5019
                                        if (newX > nextX)
5020
                                            newX = (point[0] + nextX) / 2;
5021
                                    }
5022
                                    else
5023
                                    {
5024
                                        newX = tempX - gridSetting.Length;
5025
                                        if (newX < nextX)
5026
                                            newX = (point[0] + nextX) / 2;
5027
                                    }
5028
                                    resultPoint = new double[] { newX, resultPoint[1] };
5029
                                }
5030

    
5031
                                if (bCalcY)
5032
                                {
5033
                                    double nextY = targetVertices[i - 1][1];
5034
                                    double newY = 0;
5035
                                    if (nextY > tempY)
5036
                                    {
5037
                                        newY = tempY + gridSetting.Length;
5038
                                        if (newY > nextY)
5039
                                            newY = (point[1] + nextY) / 2;
5040
                                    }
5041
                                    else
5042
                                    {
5043
                                        newY = tempY - gridSetting.Length;
5044
                                        if (newY < nextY)
5045
                                            newY = (point[1] + nextY) / 2;
5046
                                    }
5047
                                    resultPoint = new double[] { resultPoint[0], newY };
5048
                                }
5049
                            }
5050
                        }
5051
                        break;
5052
                    }
5053
                }
5054
            }
5055

    
5056
            x = resultPoint[0];
5057
            y = resultPoint[1];
5058

    
5059
            return targetConnector;
5060
        }
5061

    
5062
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
5063
        {
5064
            LMConnector result = null;
5065
            List<LMConnector> connectors = new List<LMConnector>();
5066
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5067

    
5068
            if (modelItem != null)
5069
            {
5070
                foreach (LMRepresentation rep in modelItem.Representations)
5071
                {
5072
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5073
                        connectors.Add(dataSource.GetConnector(rep.Id));
5074
                }
5075

    
5076
                ReleaseCOMObjects(modelItem);
5077
            }
5078

    
5079
            if (connectors.Count == 1)
5080
                result = connectors[0];
5081
            else
5082
                foreach (var item in connectors)
5083
                    ReleaseCOMObjects(item);
5084

    
5085
            return result;
5086
        }
5087

    
5088
        private LMConnector GetLMConnectorFirst(string modelItemID)
5089
        {
5090
            LMConnector result = null;
5091
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5092

    
5093
            if (modelItem != null)
5094
            {
5095
                foreach (LMRepresentation rep in modelItem.Representations)
5096
                {
5097
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" &&
5098
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
5099
                    {
5100
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5101
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
5102
                        {
5103
                            result = connector;
5104
                            break;
5105
                        }
5106
                        else
5107
                        {
5108
                            ReleaseCOMObjects(connector);
5109
                            connector = null;
5110
                        }
5111
                    }
5112
                }
5113
                ReleaseCOMObjects(modelItem);
5114
                modelItem = null;
5115
            }
5116

    
5117
            return result;
5118
        }
5119

    
5120
        private int GetConnectorCount(string modelItemID)
5121
        {
5122
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5123
            int result = 0;
5124
            if (modelItem != null)
5125
            {
5126
                foreach (LMRepresentation rep in modelItem.Representations)
5127
                {
5128
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5129
                        result++;
5130
                    ReleaseCOMObjects(rep);
5131
                }
5132
                ReleaseCOMObjects(modelItem);
5133
            }
5134

    
5135
            return result;
5136
        }
5137

    
5138
        public List<string> GetRepresentations(string modelItemID)
5139
        {
5140
            List<string> result = new List<string>(); ;
5141
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5142
            if (modelItem != null)
5143
            {
5144
                foreach (LMRepresentation rep in modelItem.Representations)
5145
                {
5146
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5147
                        result.Add(rep.Id);
5148
                }
5149
                ReleaseCOMObjects(modelItem);
5150
            }
5151

    
5152
            return result;
5153
        }
5154

    
5155
        private void LineNumberModeling(LineNumber lineNumber)
5156
        {
5157
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5158
            if (line != null)
5159
            {
5160
                double x = 0;
5161
                double y = 0;
5162
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
5163

    
5164
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5165
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
5166
                if (connectedLMConnector != null)
5167
                {
5168
                    Array points = new double[] { 0, x, y };
5169
                    lineNumber.SPPID.SPPID_X = x;
5170
                    lineNumber.SPPID.SPPID_Y = y;
5171
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
5172

    
5173
                    if (_LmLabelPresist != null)
5174
                    {
5175
                        _LmLabelPresist.Commit();
5176
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
5177
                        ReleaseCOMObjects(_LmLabelPresist);
5178
                    }
5179
                }
5180

    
5181
                foreach (var item in connectorVertices)
5182
                    ReleaseCOMObjects(item.Key);
5183
            }
5184
        }
5185
        private void LineNumberCorrectModeling(LineNumber lineNumber)
5186
        {
5187
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5188
            if (line == null || line.SPPID.Vertices == null)
5189
                return;
5190

    
5191
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
5192
            {
5193
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
5194
                if (removeLabel != null)
5195
                {
5196
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
5197
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
5198

    
5199
                    GridSetting gridSetting = GridSetting.GetInstance();
5200
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
5201

    
5202
                    double[] labelRange = null;
5203
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
5204
                    List<double[]> vertices = GetConnectorVertices(connector);
5205

    
5206
                    double[] resultStart = null;
5207
                    double[] resultEnd = null;
5208
                    double distance = double.MaxValue;
5209
                    for (int i = 0; i < vertices.Count - 1; i++)
5210
                    {
5211
                        double[] startPoint = vertices[i];
5212
                        double[] endPoint = vertices[i + 1];
5213
                        foreach (var item in line.SPPID.Vertices)
5214
                        {
5215
                            double[] lineStartPoint = item[0];
5216
                            double[] lineEndPoint = item[item.Count - 1];
5217

    
5218
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
5219
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
5220
                            if (tempDistance < distance)
5221
                            {
5222
                                distance = tempDistance;
5223
                                resultStart = startPoint;
5224
                                resultEnd = endPoint;
5225
                            }
5226
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
5227
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
5228
                            if (tempDistance < distance)
5229
                            {
5230
                                distance = tempDistance;
5231
                                resultStart = startPoint;
5232
                                resultEnd = endPoint;
5233
                            }
5234
                        }
5235
                    }
5236

    
5237
                    if (resultStart != null && resultEnd != null)
5238
                    {
5239
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
5240
                        double lineStartX = 0;
5241
                        double lineStartY = 0;
5242
                        double lineEndX = 0;
5243
                        double lineEndY = 0;
5244
                        double lineNumberX = 0;
5245
                        double lineNumberY = 0;
5246
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
5247
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
5248

    
5249
                        double lineX = (lineStartX + lineEndX) / 2;
5250
                        double lineY = (lineStartY + lineEndY) / 2;
5251
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
5252
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
5253

    
5254
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
5255
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
5256
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
5257
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
5258

    
5259
                        double offsetX = 0;
5260
                        double offsetY = 0;
5261
                        if (slope == SlopeType.HORIZONTAL)
5262
                        {
5263
                            // Line Number 아래
5264
                            if (lineY < lineNumberY)
5265
                            {
5266
                                offsetX = labelCenterX - SPPIDCenterX;
5267
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
5268
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5269
                            }
5270
                            // Line Number 위
5271
                            else
5272
                            {
5273
                                offsetX = labelCenterX - SPPIDCenterX;
5274
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
5275
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5276
                            }
5277
                        }
5278
                        else if (slope == SlopeType.VERTICAL)
5279
                        {
5280
                            // Line Number 오르쪽
5281
                            if (lineX < lineNumberX)
5282
                            {
5283
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
5284
                                offsetY = labelCenterY - SPPIDCenterY;
5285
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5286
                            }
5287
                            // Line Number 왼쪽
5288
                            else
5289
                            {
5290
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
5291
                                offsetY = labelCenterY - SPPIDCenterY;
5292
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5293
                            }
5294
                        }
5295

    
5296
                        if (offsetY != 0 || offsetY != 0)
5297
                        {
5298
                            if (connector.ConnectItem1SymbolObject != null &&
5299
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
5300
                            {
5301
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
5302

    
5303
                                double x1, y1, x2, y2, originX, originY;
5304
                                symbol.Range(out x1, out y1, out x2, out y2);
5305
                                symbol.GetOrigin(out originX, out originY);
5306
                                if (originX < lineNumber.SPPID.SPPID_X)
5307
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5308
                                else
5309
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5310
                            }
5311
                            else if (connector.ConnectItem2SymbolObject != null &&
5312
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
5313
                            {
5314
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
5315

    
5316
                                double x1, y1, x2, y2, originX, originY;
5317
                                symbol.Range(out x1, out y1, out x2, out y2);
5318
                                symbol.GetOrigin(out originX, out originY);
5319
                                if (originX < lineNumber.SPPID.SPPID_X)
5320
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5321
                                else
5322
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5323
                            }
5324

    
5325
                            radApp.ActiveSelectSet.RemoveAll();
5326
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
5327
                            if (dependency != null)
5328
                            {
5329
                                radApp.ActiveSelectSet.Add(dependency);
5330
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
5331
                                transform.DefineByMove2d(-offsetX, -offsetY);
5332
                                radApp.ActiveSelectSet.Transform(transform, true);
5333
                                radApp.ActiveSelectSet.RemoveAll();
5334
                            }
5335
                        }
5336

    
5337
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
5338
                        {
5339
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
5340
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
5341
                        }
5342
                    }
5343

    
5344

    
5345
                    ReleaseCOMObjects(connector);
5346
                    connector = null;
5347
                }
5348

    
5349
                ReleaseCOMObjects(removeLabel);
5350
                removeLabel = null;
5351
            }
5352
        }
5353
        /// <summary>
5354
        /// Flow Mark Modeling
5355
        /// </summary>
5356
        /// <param name="line"></param>
5357
        private void FlowMarkModeling(Line line)
5358
        {
5359
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
5360
            {
5361
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
5362
                if (connector != null)
5363
                {
5364
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
5365
                    List<double[]> vertices = GetConnectorVertices(connector);
5366
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
5367
                    double[] point = vertices[vertices.Count - 1];
5368
                    Array array = new double[] { 0, point[0], point[1] };
5369
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, null, null, LabeledItem: connector.AsLMRepresentation());
5370
                    if (_LMLabelPersist != null)
5371
                    {
5372
                        _LMLabelPersist.Commit();
5373
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
5374
                        ReleaseCOMObjects(_LMLabelPersist);
5375
                    }
5376
                }
5377
            }
5378
        }
5379

    
5380
        /// <summary>
5381
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
5382
        /// </summary>
5383
        /// <param name="lineNumber"></param>
5384
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
5385
        {
5386
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
5387
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
5388
            {
5389
                if (a.ATTRIBUTE == "Tag Seq No")
5390
                    return 1;
5391
                else if (b.ATTRIBUTE == "Tag Seq No")
5392
                    return -1;
5393

    
5394
                return 0;
5395
            }
5396

    
5397
            foreach (LineRun run in lineNumber.RUNS)
5398
            {
5399
                foreach (var item in run.RUNITEMS)
5400
                {
5401
                    if (item.GetType() == typeof(Line))
5402
                    {
5403
                        Line line = item as Line;
5404
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
5405
                        {
5406
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5407
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5408
                            {
5409
                                foreach (var attribute in lineNumber.ATTRIBUTES)
5410
                                {
5411
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
5412
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5413
                                    {
5414
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5415
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
5416
                                        {
5417
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5418
                                            if (_FluidSystemAttribute != null)
5419
                                            {
5420
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
5421
                                                if (dt.Rows.Count == 1)
5422
                                                {
5423
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5424
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5425
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5426
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5427
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5428

    
5429
                                                    if (_LMAAttribute != null)
5430
                                                    {
5431
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5432
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5433
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
5434
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5435
                                                    }
5436
                                                }
5437
                                                if (dt != null)
5438
                                                    dt.Dispose();
5439
                                            }
5440
                                        }
5441
                                        else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(attribute.VALUE) && _LMAAttribute != null)
5442
                                        {
5443
                                            DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", attribute.VALUE));
5444

    
5445
                                            if (rows.Length.Equals(1))
5446
                                            {
5447
                                                if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5448
                                                    attribute.VALUE = rows[0]["MetricStr"].ToString();
5449
                                                else
5450
                                                    attribute.VALUE = rows[0]["InchStr"].ToString();
5451

    
5452
                                                if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5453
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5454
                                                else if (_LMAAttribute.get_Value() != attribute.VALUE)
5455
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5456
                                            }
5457
                                        }
5458
                                        else if (_LMAAttribute != null)
5459
                                        {
5460
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5461
                                                _LMAAttribute.set_Value(attribute.VALUE);
5462
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
5463
                                                _LMAAttribute.set_Value(attribute.VALUE);
5464
                                        }
5465
                                    }
5466
                                }
5467
                                _LMModelItem.Commit();
5468
                            }
5469
                            if (_LMModelItem != null)
5470
                                ReleaseCOMObjects(_LMModelItem);
5471
                            endLine.Add(line.SPPID.ModelItemId);
5472
                        }
5473
                    }
5474
                }
5475
            }
5476
        }
5477

    
5478
        /// <summary>
5479
        /// Symbol Attribute 입력 메서드
5480
        /// </summary>
5481
        /// <param name="item"></param>
5482
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
5483
        {
5484
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
5485
            string sRep = null;
5486
            string sModelID = null;
5487
            if (targetItem.GetType() == typeof(Symbol))
5488
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
5489
            else if (targetItem.GetType() == typeof(Equipment))
5490
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
5491
            else if (targetItem.GetType() == typeof(Line))
5492
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
5493

    
5494
            if (!string.IsNullOrEmpty(sRep))
5495
            {
5496
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
5497
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
5498
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5499

    
5500
                foreach (var item in targetAttributes)
5501
                {
5502
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5503
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5504
                    {
5505
                        if (!mapping.IsText)
5506
                        {
5507
                            LMAAttribute _LMAAttribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5508
                            if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5509
                            {
5510
                                DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5511

    
5512
                                if (rows.Length.Equals(1))
5513
                                {
5514
                                    if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5515
                                        item.VALUE = rows[0]["MetricStr"].ToString();
5516
                                    else
5517
                                        item.VALUE = rows[0]["InchStr"].ToString();
5518

    
5519
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5520
                                        _LMAAttribute.set_Value(item.VALUE);
5521
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5522
                                        _LMAAttribute.set_Value(item.VALUE);
5523
                                }
5524
                            }
5525
                            else if (_LMAAttribute != null)
5526
                            {
5527
                                _LMAAttribute.set_Value(item.VALUE);
5528
                                // OPC 일경우 Attribute 저장
5529
                                if (targetItem.GetType() == typeof(Symbol))
5530
                                {
5531
                                    Symbol symbol = targetItem as Symbol;
5532
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
5533
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
5534
                                }
5535
                            }
5536
                        }
5537
                        else
5538
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
5539
                    }
5540
                }
5541
                _LMModelItem.Commit();
5542

    
5543
                ReleaseCOMObjects(_Attributes);
5544
                ReleaseCOMObjects(_LMModelItem);
5545
                ReleaseCOMObjects(_LMSymbol);
5546
            }
5547
            else if (!string.IsNullOrEmpty(sModelID))
5548
            {
5549
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
5550
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5551

    
5552
                foreach (var item in targetAttributes)
5553
                {
5554
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5555
                    if (mapping == null)
5556
                        continue;
5557

    
5558
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5559
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
5560
                    {
5561
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5562
                        if (_FluidSystemAttribute != null)
5563
                        {
5564
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
5565
                            if (dt.Rows.Count == 1)
5566
                            {
5567
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5568
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5569
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5570
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5571
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5572

    
5573
                                if (_LMAAttribute != null)
5574
                                {
5575
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5576
                                        _LMAAttribute.set_Value(item.VALUE);
5577
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5578
                                        _LMAAttribute.set_Value(item.VALUE);
5579
                                }
5580
                            }
5581
                            if (dt != null)
5582
                                dt.Dispose();
5583
                        }
5584
                    }
5585
                    else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5586
                    {
5587
                        DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5588

    
5589
                        if (rows.Length.Equals(1))
5590
                        {
5591
                            if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5592
                                item.VALUE = rows[0]["MetricStr"].ToString();
5593
                            else
5594
                                item.VALUE = rows[0]["InchStr"].ToString();
5595

    
5596
                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5597
                                _LMAAttribute.set_Value(item.VALUE);
5598
                            else if (_LMAAttribute.get_Value() != item.VALUE)
5599
                                _LMAAttribute.set_Value(item.VALUE);
5600
                        }
5601
                    }
5602
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5603
                    {
5604
                        if (!mapping.IsText)
5605
                        {
5606
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5607
                            if (_Attribute != null)
5608
                                _Attribute.set_Value(item.VALUE);
5609
                        }
5610
                    }
5611
                }
5612
                _LMModelItem.Commit();
5613

    
5614
                ReleaseCOMObjects(_Attributes);
5615
                ReleaseCOMObjects(_LMModelItem);
5616
            }
5617
        }
5618

    
5619
        /// <summary>
5620
        /// Input SpecBreak Attribute
5621
        /// </summary>
5622
        /// <param name="specBreak"></param>
5623
        private void InputSpecBreakAttribute(SpecBreak specBreak)
5624
        {
5625
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
5626
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
5627

    
5628
            if (upStreamObj != null &&
5629
                downStreamObj != null)
5630
            {
5631
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
5632

    
5633
                if (targetLMConnector != null)
5634
                {
5635
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
5636
                    {
5637
                        string symbolPath = _LMLabelPersist.get_FileName();
5638
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
5639
                        if (mapping != null)
5640
                        {
5641
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
5642
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5643
                            {
5644
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
5645
                                if (values.Length == 2)
5646
                                {
5647
                                    string upStreamValue = values[0];
5648
                                    string downStreamValue = values[1];
5649

    
5650
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
5651
                                }
5652
                            }
5653
                        }
5654
                    }
5655

    
5656
                    ReleaseCOMObjects(targetLMConnector);
5657
                }
5658
            }
5659

    
5660

    
5661
            #region 내부에서만 쓰는 메서드
5662
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
5663
            {
5664
                Symbol upStreamSymbol = _upStreamObj as Symbol;
5665
                Line upStreamLine = _upStreamObj as Line;
5666
                Symbol downStreamSymbol = _downStreamObj as Symbol;
5667
                Line downStreamLine = _downStreamObj as Line;
5668
                // 둘다 Line일 경우
5669
                if (upStreamLine != null && downStreamLine != null)
5670
                {
5671
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5672
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5673
                }
5674
                // 둘다 Symbol일 경우
5675
                else if (upStreamSymbol != null && downStreamSymbol != null)
5676
                {
5677
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
5678
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5679
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5680

    
5681
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5682
                    {
5683
                        if (connector.get_ItemStatus() != "Active")
5684
                            continue;
5685

    
5686
                        if (connector.Id != zeroLenthConnector.Id)
5687
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5688
                    }
5689

    
5690
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5691
                    {
5692
                        if (connector.get_ItemStatus() != "Active")
5693
                            continue;
5694

    
5695
                        if (connector.Id != zeroLenthConnector.Id)
5696
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5697
                    }
5698

    
5699
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5700
                    {
5701
                        if (connector.get_ItemStatus() != "Active")
5702
                            continue;
5703

    
5704
                        if (connector.Id != zeroLenthConnector.Id)
5705
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5706
                    }
5707

    
5708
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5709
                    {
5710
                        if (connector.get_ItemStatus() != "Active")
5711
                            continue;
5712

    
5713
                        if (connector.Id != zeroLenthConnector.Id)
5714
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5715
                    }
5716

    
5717
                    ReleaseCOMObjects(zeroLenthConnector);
5718
                    ReleaseCOMObjects(upStreamLMSymbol);
5719
                    ReleaseCOMObjects(downStreamLMSymbol);
5720
                }
5721
                else if (upStreamSymbol != null && downStreamLine != null)
5722
                {
5723
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
5724
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5725
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5726

    
5727
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5728
                    {
5729
                        if (connector.get_ItemStatus() != "Active")
5730
                            continue;
5731

    
5732
                        if (connector.Id == zeroLenthConnector.Id)
5733
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5734
                    }
5735

    
5736
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5737
                    {
5738
                        if (connector.get_ItemStatus() != "Active")
5739
                            continue;
5740

    
5741
                        if (connector.Id == zeroLenthConnector.Id)
5742
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5743
                    }
5744

    
5745
                    ReleaseCOMObjects(zeroLenthConnector);
5746
                    ReleaseCOMObjects(upStreamLMSymbol);
5747
                }
5748
                else if (upStreamLine != null && downStreamSymbol != null)
5749
                {
5750
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
5751
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5752
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5753

    
5754
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5755
                    {
5756
                        if (connector.get_ItemStatus() != "Active")
5757
                            continue;
5758

    
5759
                        if (connector.Id == zeroLenthConnector.Id)
5760
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5761
                    }
5762

    
5763
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5764
                    {
5765
                        if (connector.get_ItemStatus() != "Active")
5766
                            continue;
5767

    
5768
                        if (connector.Id == zeroLenthConnector.Id)
5769
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5770
                    }
5771

    
5772
                    ReleaseCOMObjects(zeroLenthConnector);
5773
                    ReleaseCOMObjects(downStreamLMSymbol);
5774
                }
5775
            }
5776

    
5777
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
5778
            {
5779
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5780
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5781
                {
5782
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5783
                    if (_LMAAttribute != null)
5784
                    {
5785
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5786
                            _LMAAttribute.set_Value(value);
5787
                        else if (_LMAAttribute.get_Value() != value)
5788
                            _LMAAttribute.set_Value(value);
5789
                    }
5790

    
5791
                    _LMModelItem.Commit();
5792
                }
5793
                if (_LMModelItem != null)
5794
                    ReleaseCOMObjects(_LMModelItem);
5795
            }
5796

    
5797
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
5798
            {
5799
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
5800
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5801
                {
5802
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5803
                    if (_LMAAttribute != null)
5804
                    {
5805
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5806
                            _LMAAttribute.set_Value(value);
5807
                        else if (_LMAAttribute.get_Value() != value)
5808
                            _LMAAttribute.set_Value(value);
5809
                    }
5810

    
5811
                    _LMModelItem.Commit();
5812
                }
5813
                if (_LMModelItem != null)
5814
                    ReleaseCOMObjects(_LMModelItem);
5815
            }
5816
            #endregion
5817
        }
5818

    
5819
        private void InputEndBreakAttribute(EndBreak endBreak)
5820
        {
5821
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5822
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5823

    
5824
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
5825
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
5826
            {
5827
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
5828
                if (labelPersist != null)
5829
                {
5830
                    LMRepresentation representation = labelPersist.RepresentationObject;
5831
                    if (representation != null)
5832
                    {
5833
                        LMConnector connector = dataSource.GetConnector(representation.Id);
5834
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
5835
                        string modelItemID = connector.ModelItemID;
5836
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
5837
                        {
5838
                            List<string> modelItemIDs = new List<string>();
5839
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5840
                            {
5841
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
5842
                                foreach (LMConnector item in symbol.Connect1Connectors)
5843
                                {
5844
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5845
                                        modelItemIDs.Add(item.ModelItemID);
5846
                                    ReleaseCOMObjects(item);
5847
                                }
5848
                                foreach (LMConnector item in symbol.Connect2Connectors)
5849
                                {
5850
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5851
                                        modelItemIDs.Add(item.ModelItemID);
5852
                                    ReleaseCOMObjects(item);
5853
                                }
5854
                                ReleaseCOMObjects(symbol);
5855
                                symbol = null;
5856
                            }
5857
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5858
                            {
5859
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
5860
                                foreach (LMConnector item in symbol.Connect1Connectors)
5861
                                {
5862
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5863
                                        modelItemIDs.Add(item.ModelItemID);
5864
                                    ReleaseCOMObjects(item);
5865
                                }
5866
                                foreach (LMConnector item in symbol.Connect2Connectors)
5867
                                {
5868
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5869
                                        modelItemIDs.Add(item.ModelItemID);
5870
                                    ReleaseCOMObjects(item);
5871
                                }
5872
                                ReleaseCOMObjects(symbol);
5873
                                symbol = null;
5874
                            }
5875

    
5876
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5877
                            if (modelItemIDs.Count == 1)
5878
                            {
5879
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5880
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5881
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5882
                                {
5883
                                    bool result = false;
5884
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5885
                                    {
5886
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5887
                                            result = true;
5888
                                        ReleaseCOMObjects(loop);
5889
                                    }
5890

    
5891
                                    if (result)
5892
                                    {
5893
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5894
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5895
                                        //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5896
                                        //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5897
                                        ZeroLengthModelItem.Commit();
5898
                                    }
5899
                                    else
5900
                                    {
5901
                                        List<string> loopModelItems = new List<string>();
5902
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5903
                                        {
5904
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5905
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5906
                                            {
5907
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5908
                                                    loopModelItems.Add(loop.ModelItemID);
5909
                                                ReleaseCOMObjects(loop);
5910
                                            }
5911
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5912
                                            {
5913
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5914
                                                    loopModelItems.Add(loop.ModelItemID);
5915
                                                ReleaseCOMObjects(loop);
5916
                                            }
5917
                                            ReleaseCOMObjects(_symbol);
5918
                                            _symbol = null;
5919
                                        }
5920
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5921
                                        {
5922
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5923
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5924
                                            {
5925
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5926
                                                    loopModelItems.Add(loop.ModelItemID);
5927
                                                ReleaseCOMObjects(loop);
5928
                                            }
5929
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5930
                                            {
5931
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5932
                                                    loopModelItems.Add(loop.ModelItemID);
5933
                                                ReleaseCOMObjects(loop);
5934
                                            }
5935
                                            ReleaseCOMObjects(_symbol);
5936
                                            _symbol = null;
5937
                                        }
5938

    
5939
                                        loopModelItems = loopModelItems.Distinct().ToList();
5940
                                        if (loopModelItems.Count == 1)
5941
                                        {
5942
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5943
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5944
                                            //object value2 = loopModelItem.Attributes["SubUnitNumber"].get_Value();
5945
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5946
                                            //modelItem.Attributes["SubUnitNumber"].set_Value(value2);
5947
                                            modelItem.Commit();
5948
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5949
                                            //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5950
                                            ZeroLengthModelItem.Commit();
5951

    
5952
                                            ReleaseCOMObjects(loopModelItem);
5953
                                            loopModelItem = null;
5954
                                        }
5955
                                    }
5956
                                }
5957
                                else
5958
                                {
5959
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5960
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5961
                                    //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5962
                                    //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5963
                                    ZeroLengthModelItem.Commit();
5964
                                }
5965
                                ReleaseCOMObjects(modelItem);
5966
                                modelItem = null;
5967
                                ReleaseCOMObjects(onlyOne);
5968
                                onlyOne = null;
5969
                            }
5970
                        }
5971
                        ReleaseCOMObjects(connector);
5972
                        connector = null;
5973
                        ReleaseCOMObjects(ZeroLengthModelItem);
5974
                        ZeroLengthModelItem = null;
5975
                    }
5976
                    ReleaseCOMObjects(representation);
5977
                    representation = null;
5978
                }
5979
                ReleaseCOMObjects(labelPersist);
5980
                labelPersist = null;
5981
            }
5982
        }
5983

    
5984
        /// <summary>
5985
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5986
        /// </summary>
5987
        /// <param name="text"></param>
5988
        private void NormalTextModeling(Text text)
5989
        {
5990
            LMSymbol _LMSymbol = null;
5991

    
5992
            LMItemNote _LMItemNote = null;
5993
            LMAAttribute _LMAAttribute = null;
5994

    
5995
            double x = 0;
5996
            double y = 0;
5997
            double angle = text.ANGLE;
5998
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5999

    
6000
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
6001
            text.SPPID.SPPID_X = x;
6002
            text.SPPID.SPPID_Y = y;
6003

    
6004
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
6005
            if (_LMSymbol != null)
6006
            {
6007
                _LMSymbol.Commit();
6008
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6009
                if (_LMItemNote != null)
6010
                {
6011
                    _LMItemNote.Commit();
6012
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6013
                    if (_LMAAttribute != null)
6014
                    {
6015
                        _LMAAttribute.set_Value(text.VALUE);
6016
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6017
                        _LMItemNote.Commit();
6018

    
6019

    
6020
                        double[] range = null;
6021
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6022
                        {
6023
                            double[] temp = null;
6024
                            GetSPPIDSymbolRange(labelPersist, ref temp);
6025
                            if (temp != null)
6026
                            {
6027
                                if (range == null)
6028
                                    range = temp;
6029
                                else
6030
                                {
6031
                                    range = new double[] {
6032
                                            Math.Min(range[0], temp[0]),
6033
                                            Math.Min(range[1], temp[1]),
6034
                                            Math.Max(range[2], temp[2]),
6035
                                            Math.Max(range[3], temp[3])
6036
                                        };
6037
                                }
6038
                            }
6039
                        }
6040
                        text.SPPID.Range = range;
6041

    
6042
                        if (_LMAAttribute != null)
6043
                            ReleaseCOMObjects(_LMAAttribute);
6044
                        if (_LMItemNote != null)
6045
                            ReleaseCOMObjects(_LMItemNote);
6046
                    }
6047

    
6048
                    TextCorrectModeling(text);
6049
                }
6050
            }
6051
            if (_LMSymbol != null)
6052
                ReleaseCOMObjects(_LMSymbol);
6053
        }
6054

    
6055
        private void DefaultTextModeling(string value, double x, double y)
6056
        {
6057
            LMSymbol _LMSymbol = null;
6058

    
6059
            LMItemNote _LMItemNote = null;
6060
            LMAAttribute _LMAAttribute = null;
6061

    
6062
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
6063
            if (_LMSymbol != null)
6064
            {
6065
                _LMSymbol.Commit();
6066
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6067
                if (_LMItemNote != null)
6068
                {
6069
                    _LMItemNote.Commit();
6070
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6071
                    if (_LMAAttribute != null)
6072
                    {
6073
                        _LMAAttribute.set_Value(value);
6074
                        _LMItemNote.Commit();
6075

    
6076
                        if (_LMAAttribute != null)
6077
                            ReleaseCOMObjects(_LMAAttribute);
6078
                        if (_LMItemNote != null)
6079
                            ReleaseCOMObjects(_LMItemNote);
6080
                    }
6081
                }
6082
            }
6083
            if (_LMSymbol != null)
6084
                ReleaseCOMObjects(_LMSymbol);
6085
        }
6086

    
6087
        private void AssociationTextModeling(Text text)
6088
        {
6089
            LMSymbol _LMSymbol = null;
6090
            LMConnector connectedLMConnector = null;
6091
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6092
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
6093
            {
6094
                Symbol symbol = owner as Symbol;
6095
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6096
                if (_LMSymbol != null)
6097
                {
6098
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6099
                    {
6100
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6101
                        {
6102
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6103

    
6104
                            if (mapping != null)
6105
                            {
6106
                                double x = 0;
6107
                                double y = 0;
6108

    
6109
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6110
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6111
                                Array array = new double[] { 0, x, y };
6112
                                text.SPPID.SPPID_X = x;
6113
                                text.SPPID.SPPID_Y = y;
6114
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6115
                                if (_LMLabelPersist != null)
6116
                                {
6117
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6118
                                    _LMLabelPersist.Commit();
6119
                                    ReleaseCOMObjects(_LMLabelPersist);
6120
                                }
6121
                            }
6122
                        }
6123
                    }
6124
                }
6125
            }
6126
            else if (owner != null && owner.GetType() == typeof(Line))
6127
            {
6128
                Line line = owner as Line;
6129
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
6130
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
6131

    
6132
                if (connectedLMConnector != null)
6133
                {
6134
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6135
                    {
6136
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6137
                        {
6138
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6139

    
6140
                            if (mapping != null)
6141
                            {
6142
                                double x = 0;
6143
                                double y = 0;
6144
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6145
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6146
                                Array array = new double[] { 0, x, y };
6147

    
6148
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6149
                                if (_LMLabelPersist != null)
6150
                                {
6151
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6152
                                    _LMLabelPersist.Commit();
6153

    
6154
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
6155
                                    if (dependency != null)
6156
                                    {
6157
                                        radApp.ActiveSelectSet.RemoveAll();
6158
                                        radApp.ActiveSelectSet.Add(dependency);
6159
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
6160
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
6161
                                        radApp.ActiveSelectSet.Transform(transform, true);
6162
                                        radApp.ActiveSelectSet.RemoveAll();
6163
                                    }
6164

    
6165
                                    ReleaseCOMObjects(_LMLabelPersist);
6166
                                }
6167
                            }
6168
                        }
6169
                    }
6170
                }
6171
            }
6172
            if (_LMSymbol != null)
6173
                ReleaseCOMObjects(_LMSymbol);
6174
        }
6175

    
6176
        private void TextCorrectModeling(Text text)
6177
        {
6178
            if (text.SPPID.Range == null)
6179
                return;
6180

    
6181
            bool needRemodeling = false;
6182
            bool loop = true;
6183
            GridSetting gridSetting = GridSetting.GetInstance();
6184
            while (loop)
6185
            {
6186
                loop = false;
6187
                foreach (var overlapText in document.TEXTINFOS)
6188
                {
6189
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
6190
                        continue;
6191

    
6192
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
6193
                    {
6194
                        double percentX = 0;
6195
                        double percentY = 0;
6196
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
6197
                        {
6198
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
6199
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
6200
                        }
6201
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
6202
                        {
6203
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
6204
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
6205
                        }
6206

    
6207
                        double tempX = 0;
6208
                        double tempY = 0;
6209
                        bool overlapX = false;
6210
                        bool overlapY = false;
6211
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6212
                        if (percentX >= percentY)
6213
                        {
6214
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6215
                            double move = gridSetting.Length * count;
6216
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
6217
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
6218
                            needRemodeling = true;
6219
                            loop = true;
6220
                        }
6221
                        else
6222
                        {
6223
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6224
                            double move = gridSetting.Length * count;
6225
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
6226
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
6227
                            needRemodeling = true;
6228
                            loop = true;
6229
                        }
6230
                    }
6231
                }
6232
            }
6233

    
6234

    
6235
            if (needRemodeling)
6236
            {
6237
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
6238
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6239
                text.SPPID.RepresentationId = null;
6240

    
6241
                LMItemNote _LMItemNote = null;
6242
                LMAAttribute _LMAAttribute = null;
6243
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
6244
                if (_LMSymbol != null)
6245
                {
6246
                    _LMSymbol.Commit();
6247
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6248
                    if (_LMItemNote != null)
6249
                    {
6250
                        _LMItemNote.Commit();
6251
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6252
                        if (_LMAAttribute != null)
6253
                        {
6254
                            _LMAAttribute.set_Value(text.VALUE);
6255
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6256
                            _LMItemNote.Commit();
6257

    
6258
                            ReleaseCOMObjects(_LMAAttribute);
6259
                            ReleaseCOMObjects(_LMItemNote);
6260
                        }
6261
                    }
6262
                }
6263

    
6264
                ReleaseCOMObjects(symbol);
6265
                symbol = null;
6266
                ReleaseCOMObjects(_LMItemNote);
6267
                _LMItemNote = null;
6268
                ReleaseCOMObjects(_LMAAttribute);
6269
                _LMAAttribute = null;
6270
                ReleaseCOMObjects(_LMSymbol);
6271
                _LMSymbol = null;
6272
            }
6273
        }
6274

    
6275
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
6276
        {
6277
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
6278
            {
6279
                List<Text> allTexts = new List<Text>();
6280
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6281
                LMRepresentation representation = targetLabel.RepresentationObject;
6282
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
6283
                if (targetLabel.RepresentationObject != null && symbol != null)
6284
                {
6285
                    double[] symbolRange = null;
6286
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
6287
                    if (symbolRange != null)
6288
                    {
6289
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
6290
                        {
6291
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
6292
                            if (findText != null)
6293
                            {
6294
                                double[] range = null;
6295
                                GetSPPIDSymbolRange(labelPersist, ref range);
6296
                                findText.SPPID.Range = range;
6297
                                allTexts.Add(findText);
6298
                            }
6299

    
6300
                            ReleaseCOMObjects(labelPersist);
6301
                        }
6302

    
6303
                        if (allTexts.Count > 0)
6304
                        {
6305
                            #region Sort Text By Y
6306
                            allTexts.Sort(SortTextByY);
6307
                            int SortTextByY(Text a, Text b)
6308
                            {
6309
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
6310
                            }
6311
                            #endregion
6312

    
6313
                            #region 정렬하기전 방향
6314
                            List<Text> left = new List<Text>();
6315
                            List<Text> down = new List<Text>();
6316
                            List<Text> right = new List<Text>();
6317
                            List<Text> up = new List<Text>();
6318
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
6319
                            foreach (var loopText in allTexts)
6320
                            {
6321
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
6322
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
6323
                                double originX = 0;
6324
                                double originY = 0;
6325
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6326
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6327

    
6328
                                if (angle < 45)
6329
                                {
6330
                                    // Text 오른쪽
6331
                                    if (textCenterX > originX)
6332
                                        right.Add(loopText);
6333
                                    // Text 왼쪽
6334
                                    else
6335
                                        left.Add(loopText);
6336
                                }
6337
                                else
6338
                                {
6339
                                    // Text 아래쪽
6340
                                    if (textCenterY > originY)
6341
                                        down.Add(loopText);
6342
                                    // Text 위쪽
6343
                                    else
6344
                                        up.Add(loopText);
6345
                                }
6346
                            }
6347

    
6348
                            #endregion
6349

    
6350
                            foreach (var texts in sortTexts)
6351
                            {
6352
                                if (texts.Count == 0)
6353
                                    continue;
6354

    
6355
                                #region 첫번째 Text로 기준 맞춤
6356
                                for (int i = 0; i < texts.Count; i++)
6357
                                {
6358
                                    if (i != 0)
6359
                                    {
6360
                                        Text currentText = texts[i];
6361
                                        Text prevText = texts[i - 1];
6362
                                        double minY = prevText.SPPID.Range[1];
6363
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
6364
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
6365
                                        double _gapX = centerX - centerPrevX;
6366
                                        double _gapY = currentText.SPPID.Range[3] - minY;
6367
                                        MoveText(currentText, _gapX, _gapY);
6368
                                    }
6369
                                }
6370
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
6371
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
6372
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
6373
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
6374
                                rangeMinX.Sort();
6375
                                rangeMinY.Sort();
6376
                                rangeMaxX.Sort();
6377
                                rangeMaxY.Sort();
6378
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
6379
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
6380
                                #endregion
6381
                                #region 정렬
6382
                                Text correctBySymbol = texts[0];
6383
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
6384
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
6385
                                double originX = 0;
6386
                                double originY = 0;
6387
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6388
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6389
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
6390
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
6391

    
6392
                                double gapX = 0;
6393
                                double gapY = 0;
6394
                                if (angle < 45)
6395
                                {
6396
                                    // Text 오른쪽
6397
                                    if (textCenterX > originX)
6398
                                    {
6399
                                        gapX = rangeMinX[0] - symbolRange[2];
6400
                                        gapY = allTextCenterY - symbolCenterY;
6401
                                    }
6402
                                    // Text 왼쪽
6403
                                    else
6404
                                    {
6405
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
6406
                                        gapY = allTextCenterY - symbolCenterY;
6407
                                    }
6408
                                }
6409
                                else
6410
                                {
6411
                                    // Text 아래쪽
6412
                                    if (textCenterY > originY)
6413
                                    {
6414
                                        gapX = allTextCenterX - symbolCenterX;
6415
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
6416
                                    }
6417
                                    // Text 위쪽
6418
                                    else
6419
                                    {
6420
                                        gapX = allTextCenterX - symbolCenterX;
6421
                                        gapY = rangeMinY[0] - symbolRange[3];
6422
                                    }
6423
                                }
6424

    
6425
                                foreach (var item in texts)
6426
                                {
6427
                                    MoveText(item, gapX, gapY);
6428
                                    RemodelingAssociationText(item);
6429
                                }
6430
                                #endregion
6431
                            }
6432
                        }
6433
                    }
6434
                }
6435

    
6436
                void MoveText(Text moveText, double x, double y)
6437
                {
6438
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
6439
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
6440
                    moveText.SPPID.Range = new double[] {
6441
                        moveText.SPPID.Range[0] - x,
6442
                        moveText.SPPID.Range[1]- y,
6443
                        moveText.SPPID.Range[2]- x,
6444
                        moveText.SPPID.Range[3]- y
6445
                    };
6446
                }
6447

    
6448
                endTexts.AddRange(allTexts);
6449

    
6450
                ReleaseCOMObjects(targetLabel);
6451
                targetLabel = null;
6452
                ReleaseCOMObjects(representation);
6453
                representation = null;
6454
            }
6455
        }
6456

    
6457
        private void RemodelingAssociationText(Text text)
6458
        {
6459
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6460
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
6461
            removeLabel.Commit();
6462
            ReleaseCOMObjects(removeLabel);
6463
            removeLabel = null;
6464

    
6465
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6466
            if (owner != null && owner.GetType() == typeof(Symbol))
6467
            {
6468
                Symbol symbol = owner as Symbol;
6469
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6470
                if (_LMSymbol != null)
6471
                {
6472
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
6473
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6474
                    {
6475
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6476

    
6477
                        if (mapping != null)
6478
                        {
6479
                            double x = 0;
6480
                            double y = 0;
6481

    
6482
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
6483
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6484
                            if (_LMLabelPersist != null)
6485
                            {
6486
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6487
                                _LMLabelPersist.Commit();
6488
                            }
6489
                            ReleaseCOMObjects(_LMLabelPersist);
6490
                            _LMLabelPersist = null;
6491
                        }
6492
                    }
6493
                }
6494
                ReleaseCOMObjects(_LMSymbol);
6495
                _LMSymbol = null;
6496
            }
6497
        }
6498

    
6499
        /// <summary>
6500
        /// Note Modeling
6501
        /// </summary>
6502
        /// <param name="note"></param>
6503
        private void NoteModeling(Note note, List<Note> correctList)
6504
        {
6505
            LMSymbol _LMSymbol = null;
6506
            LMItemNote _LMItemNote = null;
6507
            LMAAttribute _LMAAttribute = null;
6508

    
6509
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
6510
            {
6511
                double x = 0;
6512
                double y = 0;
6513

    
6514
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
6515
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6516
                note.SPPID.SPPID_X = x;
6517
                note.SPPID.SPPID_Y = y;
6518

    
6519
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
6520
                if (_LMSymbol != null)
6521
                {
6522
                    _LMSymbol.Commit();
6523
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6524
                    if (_LMItemNote != null)
6525
                    {
6526
                        _LMItemNote.Commit();
6527
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6528
                        if (_LMAAttribute != null)
6529
                        {
6530
                            _LMAAttribute.set_Value(note.VALUE);
6531
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6532

    
6533
                            double[] range = null;
6534
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6535
                            {
6536
                                double[] temp = null;
6537
                                GetSPPIDSymbolRange(labelPersist, ref temp);
6538
                                if (temp != null)
6539
                                {
6540
                                    if (range == null)
6541
                                        range = temp;
6542
                                    else
6543
                                    {
6544
                                        range = new double[] {
6545
                                            Math.Min(range[0], temp[0]),
6546
                                            Math.Min(range[1], temp[1]),
6547
                                            Math.Max(range[2], temp[2]),
6548
                                            Math.Max(range[3], temp[3])
6549
                                        };
6550
                                    }
6551
                                }
6552
                            }
6553
                            if (range != null)
6554
                                correctList.Add(note);
6555
                            note.SPPID.Range = range;
6556

    
6557

    
6558
                            _LMItemNote.Commit();
6559
                        }
6560
                    }
6561
                }
6562
            }
6563

    
6564
            if (_LMAAttribute != null)
6565
                ReleaseCOMObjects(_LMAAttribute);
6566
            if (_LMItemNote != null)
6567
                ReleaseCOMObjects(_LMItemNote);
6568
            if (_LMSymbol != null)
6569
                ReleaseCOMObjects(_LMSymbol);
6570
        }
6571

    
6572
        private void NoteCorrectModeling(Note note, List<Note> endList)
6573
        {
6574
            bool needRemodeling = false;
6575
            bool loop = true;
6576
            GridSetting gridSetting = GridSetting.GetInstance();
6577
            while (loop)
6578
            {
6579
                loop = false;
6580
                foreach (var overlap in endList)
6581
                {
6582
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
6583
                    {
6584
                        double tempX = 0;
6585
                        double tempY = 0;
6586
                        bool overlapX = false;
6587
                        bool overlapY = false;
6588
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6589
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
6590
                        if (overlapY && angle >= 45)
6591
                        {
6592
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6593
                            double move = gridSetting.Length * count;
6594
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
6595
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
6596
                            needRemodeling = true;
6597
                            loop = true;
6598
                        }
6599
                        if (overlapX && angle <= 45)
6600
                        {
6601
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6602
                            double move = gridSetting.Length * count;
6603
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
6604
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
6605
                            needRemodeling = true;
6606
                            loop = true;
6607
                        }
6608
                    }
6609
                }
6610
            }
6611

    
6612

    
6613
            if (needRemodeling)
6614
            {
6615
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
6616
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6617
                note.SPPID.RepresentationId = null;
6618

    
6619
                LMItemNote _LMItemNote = null;
6620
                LMAAttribute _LMAAttribute = null;
6621
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
6622
                if (_LMSymbol != null)
6623
                {
6624
                    _LMSymbol.Commit();
6625
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6626
                    if (_LMItemNote != null)
6627
                    {
6628
                        _LMItemNote.Commit();
6629
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6630
                        if (_LMAAttribute != null)
6631
                        {
6632
                            _LMAAttribute.set_Value(note.VALUE);
6633
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6634
                            _LMItemNote.Commit();
6635

    
6636
                            ReleaseCOMObjects(_LMAAttribute);
6637
                            ReleaseCOMObjects(_LMItemNote);
6638
                        }
6639
                    }
6640
                }
6641

    
6642
                ReleaseCOMObjects(symbol);
6643
                symbol = null;
6644
                ReleaseCOMObjects(_LMItemNote);
6645
                _LMItemNote = null;
6646
                ReleaseCOMObjects(_LMAAttribute);
6647
                _LMAAttribute = null;
6648
                ReleaseCOMObjects(_LMSymbol);
6649
                _LMSymbol = null;
6650
            }
6651

    
6652
            endList.Add(note);
6653
        }
6654

    
6655
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
6656
        {
6657
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6658
            if (modelItem != null)
6659
            {
6660
                foreach (LMRepresentation rep in modelItem.Representations)
6661
                {
6662
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
6663
                    {
6664
                        LMConnector connector = dataSource.GetConnector(rep.Id);
6665
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
6666
                        {
6667
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
6668
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6669
                            if (modelItemIds.Count == 1)
6670
                            {
6671
                                string joinModelItemId = modelItemIds[0];
6672
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6673
                                if (survivorId != null)
6674
                                    break;
6675
                            }
6676
                        }
6677
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
6678
                        {
6679
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
6680
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6681
                            if (modelItemIds.Count == 1)
6682
                            {
6683
                                string joinModelItemId = modelItemIds[0];
6684
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6685
                                if (survivorId != null)
6686
                                    break;
6687
                            }
6688
                        }
6689
                    }
6690
                }
6691
            }
6692
        }
6693

    
6694
        /// <summary>
6695
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
6696
        /// </summary>
6697
        /// <param name="x"></param>
6698
        /// <param name="y"></param>
6699
        /// <param name="originX"></param>
6700
        /// <param name="originY"></param>
6701
        /// <param name="SPPIDLabelLocation"></param>
6702
        /// <param name="location"></param>
6703
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDEtcLocationInfo SPPIDLabelLocation, Location location)
6704
        {
6705
            if (location == Location.None)
6706
            {
6707
                x = originX;
6708
                y = originY;
6709
            }
6710
            else
6711
            {
6712
                if (location.HasFlag(Location.Center))
6713
                {
6714
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
6715
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
6716
                }
6717

    
6718
                if (location.HasFlag(Location.Left))
6719
                    x = SPPIDLabelLocation.X1;
6720
                else if (location.HasFlag(Location.Right))
6721
                    x = SPPIDLabelLocation.X2;
6722

    
6723
                if (location.HasFlag(Location.Down))
6724
                    y = SPPIDLabelLocation.Y1;
6725
                else if (location.HasFlag(Location.Up))
6726
                    y = SPPIDLabelLocation.Y2;
6727
            }
6728
        }
6729

    
6730
        /// <summary>
6731
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
6732
        /// 1. Angle Valve
6733
        /// 2. 3개로 이루어진 Symbol Group
6734
        /// </summary>
6735
        /// <returns></returns>
6736
        private List<Symbol> GetPrioritySymbol()
6737
        {
6738
            DataTable symbolTable = document.SymbolTable;
6739
            // List에 순서대로 쌓는다.
6740
            List<Symbol> symbols = new List<Symbol>();
6741

    
6742
            // Angle Valve 부터
6743
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
6744
            {
6745
                if (!symbols.Contains(symbol))
6746
                {
6747
                    double originX = 0;
6748
                    double originY = 0;
6749

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

    
6754
                    SlopeType slopeType1 = SlopeType.None;
6755
                    SlopeType slopeType2 = SlopeType.None;
6756
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
6757
                    {
6758
                        double connectorX = 0;
6759
                        double connectorY = 0;
6760
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
6761
                        if (slopeType1 == SlopeType.None)
6762
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6763
                        else
6764
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6765
                    }
6766

    
6767
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
6768
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
6769
                        symbols.Add(symbol);
6770
                }
6771
            }
6772

    
6773
            List<Symbol> tempSymbols = new List<Symbol>();
6774
            // Conn 갯수 기준
6775
            foreach (var item in document.SYMBOLS)
6776
            {
6777
                if (!symbols.Contains(item))
6778
                    tempSymbols.Add(item);
6779
            }
6780
            tempSymbols.Sort(SPPIDUtil.SortSymbolPriority);
6781
            symbols.AddRange(tempSymbols);
6782

    
6783
            return symbols;
6784
        }
6785

    
6786
        private void SetPriorityLine(List<Line> lines)
6787
        {
6788
            lines.Sort(SortLinePriority);
6789

    
6790
            int SortLinePriority(Line a, Line b)
6791
            {
6792
                int childRetval = CompareChild(a, b);
6793
                if (childRetval != 0)
6794
                {
6795
                    return childRetval;
6796
                }
6797
                else
6798
                { 
6799
                    // Branch 없는것부터
6800
                    int branchRetval = CompareBranchLine(a, b);
6801
                    if (branchRetval != 0)
6802
                    {
6803
                        return branchRetval;
6804
                    }
6805
                    else
6806
                    {
6807
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
6808
                        int connItemRetval = CompareConnItem(a, b);
6809
                        if (connItemRetval != 0)
6810
                        {
6811
                            return connItemRetval;
6812
                        }
6813
                        else
6814
                        {
6815
                            // line 길이
6816
                            int lengthRetval = CompareLength(a, b);
6817
                            if (lengthRetval != 0)
6818
                            {
6819
                                return lengthRetval;
6820
                            }
6821
                            else
6822
                            {
6823
                                // Symbol 연결 갯수
6824
                                int connSymbolRetval = CompareConnSymbol(a, b);
6825
                                if (connSymbolRetval != 0)
6826
                                {
6827
                                    return connSymbolRetval;
6828
                                }
6829
                                else
6830
                                {
6831
                                    // ConnectedItem이 없는것
6832
                                    int noneConnRetval = CompareNoneConn(a, b);
6833
                                    if (noneConnRetval != 0)
6834
                                    {
6835
                                        return noneConnRetval;
6836
                                    }
6837
                                    else
6838
                                    {
6839

    
6840
                                    }
6841
                                }
6842
                            }
6843
                        }
6844
                    }
6845
                }
6846

    
6847
                return 0;
6848
            }
6849

    
6850
            int CompareChild(Line a, Line b)
6851
            {
6852
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6853
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
6854

    
6855
                // 내림차순
6856
                return countA.CompareTo(countB);
6857
            }
6858

    
6859
            int CompareConnSymbol(Line a, Line b)
6860
            {
6861
                List<Connector> connectorsA = a.CONNECTORS
6862
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6863
                    .ToList();
6864

    
6865
                List<Connector> connectorsB = b.CONNECTORS
6866
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6867
                    .ToList();
6868

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

    
6873
            int CompareLength(Line a, Line b)
6874
            {
6875
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6876
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6877

    
6878
                // 오름차순
6879
                return lengthB.CompareTo(lengthA);
6880
            }
6881

    
6882
            int CompareConnItem(Line a, Line b)
6883
            {
6884
                List<Connector> connectorsA = a.CONNECTORS
6885
                    .Where(conn => conn.ConnectedObject != null &&
6886
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6887
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6888
                    .ToList();
6889

    
6890
                List<Connector> connectorsB = b.CONNECTORS
6891
                    .Where(conn => conn.ConnectedObject != null &&
6892
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6893
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6894
                    .ToList();
6895

    
6896
                // 내림차순
6897
                return connectorsA.Count.CompareTo(connectorsB.Count);
6898
            }
6899

    
6900
            int CompareBranchLine(Line a, Line b)
6901
            {
6902
                List<Connector> connectorsA = a.CONNECTORS
6903
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6904
                    .ToList();
6905
                List<Connector> connectorsB = b.CONNECTORS
6906
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6907
                    .ToList();
6908

    
6909
                // 내림차순
6910
                return connectorsA.Count.CompareTo(connectorsB.Count);
6911
            }
6912

    
6913
            int CompareNoneConn(Line a, Line b)
6914
            {
6915
                List<Connector> connectorsA = a.CONNECTORS
6916
                    .Where(conn => conn.ConnectedObject == null)
6917
                    .ToList();
6918

    
6919
                List<Connector> connectorsB = b.CONNECTORS
6920
                    .Where(conn => conn.ConnectedObject == null)
6921
                    .ToList();
6922

    
6923
                // 내림차순
6924
                return connectorsA.Count.CompareTo(connectorsB.Count);
6925
            }
6926
        }
6927

    
6928
        private void SortText(List<Text> texts)
6929
        {
6930
            texts.Sort(Sort);
6931

    
6932
            int Sort(Text a, Text b)
6933
            {
6934
                int yRetval = CompareY(a, b);
6935
                if (yRetval != 0)
6936
                {
6937
                    return yRetval;
6938
                }
6939
                else
6940
                {
6941
                    return CompareX(a, b);
6942
                }
6943
            }
6944

    
6945
            int CompareY(Text a, Text b)
6946
            {
6947
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6948
            }
6949

    
6950
            int CompareX(Text a, Text b)
6951
            {
6952
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6953
            }
6954
        }
6955
        private void SortNote(List<Note> notes)
6956
        {
6957
            notes.Sort(Sort);
6958

    
6959
            int Sort(Note a, Note b)
6960
            {
6961
                int yRetval = CompareY(a, b);
6962
                if (yRetval != 0)
6963
                {
6964
                    return yRetval;
6965
                }
6966
                else
6967
                {
6968
                    return CompareX(a, b);
6969
                }
6970
            }
6971

    
6972
            int CompareY(Note a, Note b)
6973
            {
6974
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6975
            }
6976

    
6977
            int CompareX(Note a, Note b)
6978
            {
6979
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6980
            }
6981
        }
6982

    
6983
        private void SortBranchLines()
6984
        {
6985
            BranchLines.Sort(SortBranchLine);
6986

    
6987
            int SortBranchLine(Line a, Line b)
6988
            {
6989
                int childRetval = CompareChild(a, b);
6990
                if (childRetval != 0)
6991
                {
6992
                    return childRetval;
6993
                }
6994
                else
6995
                {
6996
                    int branchRetval = CompareChildBranch(a, b);
6997
                    if (branchRetval != 0)
6998
                    {
6999
                        return branchRetval;
7000
                    }
7001
                    else
7002
                    {
7003
                        // line 길이
7004
                        int lengthRetval = CompareLength(a, b);
7005
                        if (lengthRetval != 0)
7006
                        {
7007
                            return lengthRetval;
7008
                        }
7009
                    }
7010
                }
7011
                return 0;
7012
            }
7013

    
7014
            int CompareLength(Line a, Line b)
7015
            {
7016
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
7017
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
7018

    
7019
                // 오름차순
7020
                return lengthB.CompareTo(lengthA);
7021
            }
7022

    
7023
            int CompareChildBranch(Line a, Line b)
7024
            {
7025
                int countA = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
7026
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == a));
7027

    
7028
                int countB = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
7029
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == b));
7030

    
7031
                // 오름차순
7032
                return countB.CompareTo(countA);
7033
            }
7034

    
7035
            int CompareChild(Line a, Line b)
7036
            {
7037
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
7038
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
7039

    
7040
                // 내림차순
7041
                return countA.CompareTo(countB);
7042
            }
7043
        }
7044

    
7045
        private string GetSPPIDFileName(LMModelItem modelItem)
7046
        {
7047
            string symbolPath = null;
7048
            foreach (LMRepresentation rep in modelItem.Representations)
7049
            {
7050
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
7051
                {
7052
                    symbolPath = rep.get_FileName();
7053
                    break;
7054
                }
7055
            }
7056
            return symbolPath;
7057
        }
7058

    
7059
        private string GetSPPIDFileName(string modelItemId)
7060
        {
7061
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
7062
            string symbolPath = null;
7063
            foreach (LMRepresentation rep in modelItem.Representations)
7064
            {
7065
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
7066
                {
7067
                    symbolPath = rep.get_FileName();
7068
                    break;
7069
                }
7070
            }
7071
            ReleaseCOMObjects(modelItem);
7072
            return symbolPath;
7073
        }
7074

    
7075
        /// <summary>
7076
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
7077
        /// </summary>
7078
        /// <param name="graphicOID"></param>
7079
        /// <param name="milliseconds"></param>
7080
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
7081
        {
7082
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
7083
            {
7084
                double minX = 0;
7085
                double minY = 0;
7086
                double maxX = 0;
7087
                double maxY = 0;
7088
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
7089
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
7090

    
7091
                Thread.Sleep(milliseconds);
7092
            }
7093
        }
7094

    
7095
        /// <summary>
7096
        /// ComObject를 Release
7097
        /// </summary>
7098
        /// <param name="objVars"></param>
7099
        public void ReleaseCOMObjects(params object[] objVars)
7100
        {
7101
            if (objVars != null)
7102
            {
7103
                int intNewRefCount = 0;
7104
                foreach (object obj in objVars)
7105
                {
7106
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
7107
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
7108
                }
7109
            }
7110
        }
7111

    
7112
        /// IDisposable 구현
7113
        ~AutoModeling()
7114
        {
7115
            this.Dispose(false);
7116
        }
7117

    
7118
        private bool disposed;
7119
        public void Dispose()
7120
        {
7121
            this.Dispose(true);
7122
            GC.SuppressFinalize(this);
7123
        }
7124

    
7125
        protected virtual void Dispose(bool disposing)
7126
        {
7127
            if (this.disposed) return;
7128
            if (disposing)
7129
            {
7130
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
7131
            }
7132
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
7133
            this.disposed = true;
7134
        }
7135
    }
7136
}
클립보드 이미지 추가 (최대 크기: 500 MB)