프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 37c2875e

이력 | 보기 | 이력해설 | 다운로드 (332 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<string> ZeroLengthModelItemID = new List<string>();
57
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
58
        List<Symbol> prioritySymbols;
59
        List<string> FlowMarkRepIds = new List<string>();
60

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

    
67
            this.closeDocument = closeDocument;
68
            this.document = document;
69
            this._ETCSetting = ETCSetting.GetInstance();
70
        }
71

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

    
84
                }
85
            }
86
        }
87

    
88
        /// <summary>
89
        /// 도면 단위당 실행되는 메서드
90
        /// </summary>
91
        public void Run()
92
        {
93
            string drawingNumber = document.DrawingNumber;
94
            string drawingName = document.DrawingName;
95
            try
96
            {
97
                radApp.Interactive = false;
98

    
99
                nominalDiameterTable = Project_DB.SelectProjectNominalDiameter();
100
                _placement = new Placement();
101
                dataSource = _placement.PIDDataSource;
102

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

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

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

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

    
203
                Project_DB.InsertDrawingInfoAndOPCInfo(document.PATH, drawingNumber, drawingName, document);
204
                //Project_DB.InsertLineNumberInfo(document.PATH, drawingNumber, drawingName, document);
205

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

    
214
                Log.Write("End Modeling");
215
                radApp.ActiveWindow.Fit();
216

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

    
235
                ReleaseCOMObjects(dataSource);
236
                dataSource = null;
237
                ReleaseCOMObjects(_placement);
238
                _placement = null;
239

    
240
                Thread.Sleep(1000);
241
            }
242
        }
243

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

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

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

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

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

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

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

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

    
499
                                    // 제거
500
                                    RemoveSymbol(connSymbol);
501
                                    RemoveLine(item);
502

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

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

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

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

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

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

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

    
684
                LMRelationships relationships = new LMRelationships();
685
                relationships.Collect(dataSource, Filter: filter);
686

    
687
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
688
                if (count > 1)
689
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
690
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
691
                foreach (LMRelationship relationship in relationships)
692
                {
693
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
694
                    {
695
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
696
                        {
697
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
698
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
699
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
700
                            if (modelItem1 != null)
701
                            {
702
                                string attrName = array[0];
703
                                if (attrName.Contains("PipingPoint"))
704
                                {
705
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
706
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
707
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
708
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
709
                                    {
710
                                        loop = true;
711
                                        attribute1.set_Value(DBNull.Value);
712
                                    }
713
                                    attribute1 = null;
714
                                }
715
                                else
716
                                {
717
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
718
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
719
                                    {
720
                                        loop = true;
721
                                        attribute1.set_Value(DBNull.Value);
722
                                    }
723
                                    attribute1 = null;
724
                                }
725
                                modelItem1.Commit();
726
                            }
727
                            if (modelItem2 != null)
728
                            {
729
                                string attrName = array[1];
730
                                if (attrName.Contains("PipingPoint"))
731
                                {
732
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
733
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
734
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
735
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
736
                                    {
737
                                        attribute2.set_Value(DBNull.Value);
738
                                        loop = true;
739
                                    }
740
                                    attribute2 = null;
741
                                }
742
                                else
743
                                {
744
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
745
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
746
                                    {
747
                                        attribute2.set_Value(DBNull.Value);
748
                                        loop = true;
749
                                    }
750
                                    attribute2 = null;
751
                                }
752
                                modelItem2.Commit();
753
                            }
754
                            ReleaseCOMObjects(modelItem1);
755
                            modelItem1 = null;
756
                            ReleaseCOMObjects(modelItem2);
757
                            modelItem2 = null;
758
                            inconsistency.Commit();
759
                        }
760
                        ReleaseCOMObjects(inconsistency);
761
                    }
762
                    relationship.Commit();
763
                    ReleaseCOMObjects(relationship);
764
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
765
                }
766
                ReleaseCOMObjects(filter);
767
                filter = null;
768
                ReleaseCOMObjects(criterion);
769
                criterion = null;
770
                ReleaseCOMObjects(relationships);
771
                relationships = null;
772
                count++;
773
            }
774
        }
775
        private void RunEndBreakModeling()
776
        {
777
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
778
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
779
            foreach (var item in document.EndBreaks)
780
                try
781
                {
782
                    EndBreakModeling(item);
783
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
784
                }
785
                catch (Exception ex)
786
                {
787
                    Log.Write("Error in EndBreakModeling");
788
                    Log.Write("UID : " + item.UID);
789
                    Log.Write(ex.Message);
790
                    Log.Write(ex.StackTrace);
791
                }
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
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
838
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
839
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
840
                            !SPPIDUtil.IsSegment(document, line, connLine))
841
                        {
842
                            string survivorId = string.Empty;
843
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
844
                        }
845

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

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

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

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

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

    
1094
            }
1095

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

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

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

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

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

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

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

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

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

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

    
1291
                        drawingAttributeDT.Dispose();
1292
                    }
1293

    
1294
                    ReleaseCOMObjects(drawing);
1295
                }
1296

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

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

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

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

    
1331
                }
1332
            }
1333
        }
1334

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

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

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

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

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

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

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

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

    
1438
            LMSymbol _LMSymbol = null;
1439

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1704
            return info;
1705
        }
1706

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

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

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

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

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

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

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

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

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

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

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

    
1811
            ReleaseCOMObjects(_TargetItem);
1812
        }
1813

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

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

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

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

    
1856
            ReleaseCOMObjects(_TargetItem);
1857
        }
1858

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

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

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

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

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

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

    
1985
            }
1986
        }
1987

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

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

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

    
2005
            range = tempRange;
2006
        }
2007

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

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

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

    
2042
                ReleaseCOMObjects(_ChildSymbol);
2043
            }
2044
        }
2045

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

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

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

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

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

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

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

    
2139
                                        if (result)
2140
                                            break;
2141
                                    }
2142

    
2143
                                    if (result)
2144
                                        break;
2145
                                }
2146
                            }
2147

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

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

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

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

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

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

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

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

    
2214
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
2215

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

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

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

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

    
2272
            if (targetItem != null)
2273
            {
2274
                ReleaseCOMObjects(targetItem);
2275
            }
2276

    
2277
            ReleaseCOMObjects(_LMSymbol);
2278
        }
2279

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

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

    
2296
                ReleaseCOMObjects(symbol);
2297
                symbol = null;
2298
            }
2299
        }
2300

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2577

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

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

    
2591
            for (int i = 0; i < group.Count; i++)
2592
            {
2593
                var currentLine = group[i];
2594

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

    
2612
                bool diagonal = false;
2613
                if (currentLine.SlopeType != SlopeType.HORIZONTAL && currentLine.SlopeType != SlopeType.VERTICAL)
2614
                    diagonal = true;
2615
                _LMAItem _LMAItem = _placement.PIDCreateItem(currentLine.SPPID.MAPPINGNAME);
2616
                LMSymbol _LMSymbolStart = null;
2617
                LMSymbol _LMSymbolEnd = null;
2618
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2619
                foreach (var connector in currentLine.CONNECTORS)
2620
                {
2621
                    double x = 0;
2622
                    double y = 0;
2623
                    GetTargetLineConnectorPoint(connector, currentLine, ref x, ref y);
2624
                    if (connector.ConnectedObject == null)
2625
                        placeRunInputs.AddPoint(x, y);
2626
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2627
                    {
2628
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2629
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == currentLine), targetSymbol, ref x, ref y);
2630
                        if (currentLine.CONNECTORS.IndexOf(connector) == 0)
2631
                        {
2632
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, currentLine);
2633
                            if (_LMSymbolStart != null)
2634
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2635
                            else
2636
                                placeRunInputs.AddPoint(x, y);
2637
                        }
2638
                        else
2639
                        {
2640
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, currentLine);
2641
                            if (_LMSymbolEnd != null)
2642
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2643
                            else
2644
                                placeRunInputs.AddPoint(x, y);
2645
                        }
2646
                    }
2647
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2648
                    {
2649
                        Line targetLine = connector.ConnectedObject as Line;
2650
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2651
                        {
2652
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(currentLine, targetLine, ref x, ref y);
2653
                            if (targetConnector != null)
2654
                            {
2655
                                if (targetLine.SlopeType != SlopeType.HORIZONTAL && targetLine.SlopeType != SlopeType.VERTICAL)
2656
                                    placeRunInputs.AddConnectorTarget(targetConnector, x, y, true);
2657
                                else
2658
                                    placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2659
                                ChangeLineSPPIDCoordinateByConnector(currentLine, targetLine, x, y, false);
2660
                            }
2661
                            else
2662
                            {
2663
                                placeRunInputs.AddPoint(x, y);
2664
                                ChangeLineSPPIDCoordinateByConnector(currentLine, targetLine, x, y, false);
2665
                            }
2666
                        }
2667
                        else
2668
                        {
2669
                            if (currentLine.CONNECTORS.IndexOf(connector) == 0)
2670
                            {
2671
                                index += 0.01;
2672
                                if (currentLine.SlopeType == SlopeType.HORIZONTAL)
2673
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2674
                                else if (currentLine.SlopeType == SlopeType.VERTICAL)
2675
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2676
                                else
2677
                                {
2678
                                    Line nextLine = currentLine.CONNECTORS[0].ConnectedObject as Line;
2679
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2680
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2681
                                    else
2682
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2683
                                }
2684
                            }
2685

    
2686
                            placeRunInputs.AddPoint(x, y);
2687

    
2688
                            if (currentLine.CONNECTORS.IndexOf(connector) == 1)
2689
                            {
2690
                                index += 0.01;
2691
                                if (currentLine.SlopeType == SlopeType.HORIZONTAL)
2692
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2693
                                else if (currentLine.SlopeType == SlopeType.VERTICAL)
2694
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2695
                                else
2696
                                {
2697
                                    Line nextLine = currentLine.CONNECTORS[1].ConnectedObject as Line;
2698
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2699
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2700
                                    else
2701
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2702
                                }
2703
                            }
2704
                        }
2705
                    }
2706
                    else
2707
                        placeRunInputs.AddPoint(x, y);
2708
                }
2709

    
2710
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2711
                if (_lMConnector != null)
2712
                {
2713
                    _lMConnector.Commit();
2714
                    currentLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2715

    
2716
                    bool bRemodelingStart = false;
2717
                    if (_LMSymbolStart != null)
2718
                        NeedReModeling(currentLine, _LMSymbolStart, ref bRemodelingStart);
2719
                    bool bRemodelingEnd = false;
2720
                    if (_LMSymbolEnd != null)
2721
                        NeedReModeling(currentLine, _LMSymbolEnd, ref bRemodelingEnd);
2722

    
2723
                    if (bRemodelingStart || bRemodelingEnd)
2724
                        ReModelingLine(currentLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2725

    
2726
                    FlowMarkModeling(currentLine);
2727

    
2728
                    ReleaseCOMObjects(_lMConnector);
2729

    
2730
                    LMModelItem modelItem = dataSource.GetModelItem(currentLine.SPPID.ModelItemId);
2731
                    if (modelItem != null)
2732
                    {
2733
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2734
                        if (attribute != null)
2735
                            attribute.set_Value("End 1 is upstream (Inlet)");
2736
                        modelItem.Commit();
2737
                    }
2738
                    ReleaseCOMObjects(modelItem);
2739
                    modelItem = null;
2740
                }
2741
                else if (!isBranchModeling)
2742
                {
2743
                    Log.Write("Main Line Modeling : " + currentLine.UID);
2744
                }
2745

    
2746
                List<object> removeLines = currentLine.CONNECTORS.FindAll(x =>
2747
                x.ConnectedObject != null &&
2748
                x.ConnectedObject.GetType() == typeof(Line) &&
2749
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2750
                .Select(x => x.ConnectedObject)
2751
                .ToList();
2752

    
2753
                foreach (var item in removeLines)
2754
                    RemoveLineForModeling(item as Line);
2755

    
2756
                ReleaseCOMObjects(_LMAItem);
2757
                _LMAItem = null;
2758
                ReleaseCOMObjects(placeRunInputs);
2759
                placeRunInputs = null;
2760
                ReleaseCOMObjects(_LMSymbolStart);
2761
                _LMSymbolStart = null;
2762
                ReleaseCOMObjects(_LMSymbolEnd);
2763
                _LMSymbolEnd = null;
2764
            }
2765
        }
2766

    
2767
        private LMConnector JustLineModeling(Line line)
2768
        {
2769
            bool diagonal = false;
2770
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2771
                diagonal = true;
2772
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2773
            LMSymbol _LMSymbolStart = null;
2774
            LMSymbol _LMSymbolEnd = null;
2775
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2776
            foreach (var connector in line.CONNECTORS)
2777
            {
2778
                double x = 0;
2779
                double y = 0;
2780
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2781
                if (connector.ConnectedObject == null)
2782
                {
2783
                    placeRunInputs.AddPoint(x, y);
2784
                }
2785
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2786
                {
2787
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2788
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2789
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2790
                    {
2791
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2792
                        if (_LMSymbolStart != null)
2793
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2794
                        else
2795
                            placeRunInputs.AddPoint(x, y);
2796
                    }
2797
                    else
2798
                    {
2799
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2800
                        if (_LMSymbolEnd != null)
2801
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2802
                        else
2803
                            placeRunInputs.AddPoint(x, y);
2804
                    }
2805
                }
2806
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2807
                {
2808
                    Line targetLine = connector.ConnectedObject as Line;
2809
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2810
                    {
2811
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2812
                        if (targetConnector != null)
2813
                        {
2814
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2815
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2816
                        }
2817
                        else
2818
                        {
2819
                            placeRunInputs.AddPoint(x, y);
2820
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2821
                        }
2822
                    }
2823
                    else
2824
                        placeRunInputs.AddPoint(x, y);
2825
                }
2826
            }
2827

    
2828
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2829
            if (_lMConnector != null)
2830
                _lMConnector.Commit();
2831

    
2832
            ReleaseCOMObjects(_LMAItem);
2833
            _LMAItem = null;
2834
            ReleaseCOMObjects(placeRunInputs);
2835
            placeRunInputs = null;
2836
            ReleaseCOMObjects(_LMSymbolStart);
2837
            _LMSymbolStart = null;
2838
            ReleaseCOMObjects(_LMSymbolEnd);
2839
            _LMSymbolEnd = null;
2840

    
2841
            return _lMConnector;
2842
        }
2843

    
2844
        private void RemoveLineForModeling(Line line)
2845
        {
2846
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2847
            if (modelItem != null)
2848
            {
2849
                foreach (LMRepresentation rep in modelItem.Representations)
2850
                {
2851
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2852
                    {
2853
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2854
                        dynamic OID = rep.get_GraphicOID().ToString();
2855
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2856
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2857
                        int verticesCount = lineStringGeometry.VertexCount;
2858
                        double[] vertices = null;
2859
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2860
                        for (int i = 0; i < verticesCount; i++)
2861
                        {
2862
                            double x = 0;
2863
                            double y = 0;
2864
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2865
                            if (verticesCount == 2 && (x < 0 || y < 0))
2866
                                _placement.PIDRemovePlacement(rep);
2867
                        }
2868
                        ReleaseCOMObjects(_LMConnector);
2869
                    }
2870
                }
2871

    
2872
                ReleaseCOMObjects(modelItem);
2873
            }
2874
        }
2875

    
2876
        private void RemoveLine(Line line)
2877
        {
2878
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2879
            if (modelItem != null)
2880
            {
2881
                foreach (LMRepresentation rep in modelItem.Representations)
2882
                {
2883
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2884
                        _placement.PIDRemovePlacement(rep);
2885
                }
2886
                ReleaseCOMObjects(modelItem);
2887
            }
2888
            line.SPPID.ModelItemId = null;
2889
        }
2890

    
2891
        private void GetConnectedLineGroup(Line line, List<Line> group)
2892
        {
2893
            if (!group.Contains(line))
2894
                group.Add(line);
2895

    
2896
            foreach (var connector in line.CONNECTORS)
2897
            {
2898
                if (connector.ConnectedObject != null &&
2899
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2900
                    !group.Contains(connector.ConnectedObject) &&
2901
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2902
                {
2903
                    Line connLine = connector.ConnectedObject as Line;
2904
                    if (line.CONNECTORS.IndexOf(connector) == 0
2905
                    && (!SPPIDUtil.IsBranchLine(connLine, line)))
2906
                    {
2907

    
2908
                        group.Insert(group.IndexOf(line), connLine);
2909
                        GetConnectedLineGroup(connLine, group);
2910
                    }
2911
                    else if (line.CONNECTORS.IndexOf(connector) == 1 && !SPPIDUtil.IsBranchLine(connLine, line))
2912
                    {
2913
                        group.Add(connLine);
2914
                        GetConnectedLineGroup(connLine, group);
2915
                    }
2916
                }
2917
            }
2918
        }
2919

    
2920
        private void LineCoordinateCorrection(List<Line> group)
2921
        {
2922
            // 순서대로 전 Item 기준 정렬
2923
            LineCoordinateCorrectionByStart(group);
2924

    
2925
            // 역으로 심볼이 있을 경우 좌표 보정
2926
            LineCoordinateCorrectionForLastLine(group);
2927
        }
2928

    
2929
        private void LineCoordinateCorrectionByStart(List<Line> group)
2930
        {
2931
            for (int i = 0; i < group.Count; i++)
2932
            {
2933
                Line line = group[i];
2934
                if (i == 0)
2935
                {
2936
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2937
                    if (symbolConnector != null)
2938
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2939
                }
2940
                else if (i != 0)
2941
                {
2942
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2943
                }
2944
            }
2945
        }
2946

    
2947
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2948
        {
2949
            Line checkLine = group[group.Count - 1];
2950
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2951
            if (lastSymbolConnector != null)
2952
            {
2953
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2954
                for (int i = group.Count - 2; i >= 0; i--)
2955
                {
2956
                    Line refLine = group[i + 1];
2957
                    Line changeline = group[i];
2958
                    LineCoordinateCorrectionByConnItem(changeline, refLine);
2959
                }
2960
            }
2961
        }
2962

    
2963
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2964
        {
2965
            double x = 0;
2966
            double y = 0;
2967
            if (connItem.GetType() == typeof(Symbol))
2968
            {
2969
                Symbol targetSymbol = connItem as Symbol;
2970
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2971
                if (targetConnector != null)
2972
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2973
                else
2974
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2975
            }
2976
            else if (connItem.GetType() == typeof(Line))
2977
            {
2978
                Line targetLine = connItem as Line;
2979
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2980
            }
2981

    
2982
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2983
        }
2984

    
2985
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2986
        {
2987
            if (line.UID == "52391a93-957c-49d1-87a1-d037e91d386c")
2988
                line.UID = line.UID;
2989

    
2990
            bool isReverseX = line.SPPID.END_X - line.SPPID.START_X < 0;
2991
            bool isReverseY = line.SPPID.END_Y - line.SPPID.START_Y < 0;
2992
            double minLength = GridSetting.GetInstance().Length * 0.5;
2993
            double minLengthX = minLength * (!isReverseX ? 1 : -1);
2994
            double minLengthY = minLength * (!isReverseY ? 1 : -1);
2995

    
2996
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2997
            int index = line.CONNECTORS.IndexOf(connector);
2998
            if (index == 0)
2999
            {
3000
                line.SPPID.START_X = x;
3001
                line.SPPID.START_Y = y;
3002
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
3003
                {
3004
                    line.SPPID.END_Y = y;
3005
                    if (line.CONNECTORS[1].ConnectedObject != null)
3006
                    {
3007
                        if (line.CONNECTORS[1].ConnectedObject.GetType() == typeof(Line))
3008
                        {
3009
                            // START_X가 END_X 값을 벗어날 경우 END_X 값 보정
3010
                            if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= minLength)
3011
                            {
3012
                                line.SPPID.END_X = line.SPPID.START_X + minLengthX;
3013
                            }
3014
                        }
3015
                        else if (line.CONNECTORS[1].ConnectedObject.GetType() == typeof(Symbol))
3016
                        {
3017
                            double x1 = 0;
3018
                            double y1 = 0;
3019
                            GetTargetSymbolConnectorPoint(line.CONNECTORS[1], (Symbol)line.CONNECTORS[1].ConnectedObject, ref x1, ref y1);
3020
                            line.SPPID.END_X = x1;
3021
                            line.SPPID.END_Y = y1;
3022
                        }
3023
                    }
3024
                }
3025
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
3026
                {
3027
                    line.SPPID.END_X = x;
3028
                    if (line.CONNECTORS[1].ConnectedObject != null)
3029
                    {
3030
                        if (line.CONNECTORS[1].ConnectedObject.GetType() == typeof(Line))
3031
                        {
3032
                            // START_Y가 END_Y 값을 벗어날 경우 END_Y 값 보정
3033
                            if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= minLength)
3034
                            {
3035
                                line.SPPID.END_Y = line.SPPID.START_Y + minLengthY;
3036
                            }
3037
                        }
3038
                        else if (line.CONNECTORS[1].ConnectedObject.GetType() == typeof(Symbol))
3039
                        {
3040
                            double x1 = 0;
3041
                            double y1 = 0;
3042
                            GetTargetSymbolConnectorPoint(line.CONNECTORS[1], (Symbol)line.CONNECTORS[1].ConnectedObject, ref x1, ref y1);
3043
                            line.SPPID.END_X = x1;
3044
                            line.SPPID.END_Y = y1;
3045
                        }
3046
                    }
3047
                }
3048
            }
3049
            else
3050
            {
3051
                line.SPPID.END_X = x;
3052
                line.SPPID.END_Y = y;
3053
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
3054
                {
3055
                    line.SPPID.START_Y = y;
3056
                    if (line.CONNECTORS[0].ConnectedObject != null)
3057
                    {
3058
                        if (line.CONNECTORS[0].ConnectedObject.GetType() == typeof(Line))
3059
                        {
3060
                            // END_X가 START_X 값을 벗어날 경우 START_X 값 보정
3061
                            if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= minLength)
3062
                            {
3063
                                line.SPPID.START_X = line.SPPID.END_X - minLengthX;
3064
                            }
3065
                        }
3066
                        else if (line.CONNECTORS[0].ConnectedObject.GetType() == typeof(Symbol))
3067
                        {
3068
                            double x1 = 0;
3069
                            double y1 = 0;
3070
                            GetTargetSymbolConnectorPoint(line.CONNECTORS[0], (Symbol)line.CONNECTORS[0].ConnectedObject, ref x1, ref y1);
3071
                            line.SPPID.END_X = x1;
3072
                            line.SPPID.END_Y = y1;
3073
                        }
3074
                    }
3075
                }
3076
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
3077
                {
3078
                    line.SPPID.START_X = x;
3079
                    if (line.CONNECTORS[0].ConnectedObject != null)
3080
                    {
3081
                        if (line.CONNECTORS[0].ConnectedObject.GetType() == typeof(Line))
3082
                        {
3083
                            // END_Y가 START_Y 값을 벗어날 경우 START_Y 값 보정
3084
                            if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= minLength)
3085
                            {
3086
                                line.SPPID.START_Y = line.SPPID.END_Y - minLengthY;
3087
                            }
3088
                        }
3089
                        else if (line.CONNECTORS[0].ConnectedObject.GetType() == typeof(Symbol))
3090
                        {
3091
                            double x1 = 0;
3092
                            double y1 = 0;
3093
                            GetTargetSymbolConnectorPoint(line.CONNECTORS[0], (Symbol)line.CONNECTORS[0].ConnectedObject, ref x1, ref y1);
3094
                            line.SPPID.END_X = x1;
3095
                            line.SPPID.END_Y = y1;
3096
                        }
3097
                    }
3098
                }
3099
            }
3100
        }
3101

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

    
3120
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
3121
        {
3122
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3123
            int index = line.CONNECTORS.IndexOf(connector);
3124
            if (index == 0)
3125
            {
3126
                line.SPPID.START_Y = y;
3127
                if (line.SlopeType == SlopeType.HORIZONTAL)
3128
                    line.SPPID.END_Y = y;
3129
            }
3130
            else
3131
            {
3132
                line.SPPID.END_Y = y;
3133
                if (line.SlopeType == SlopeType.HORIZONTAL)
3134
                    line.SPPID.START_Y = y;
3135
            }
3136
        }
3137

    
3138
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
3139
        {
3140
            if (symbol != null)
3141
            {
3142
                string repID = symbol.AsLMRepresentation().Id;
3143
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
3144
                string lineUID = line.UID;
3145

    
3146
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
3147
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
3148
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
3149

    
3150
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
3151
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
3152
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
3153

    
3154
                if (startSpecBreak != null || startEndBreak != null)
3155
                    result = true;
3156
            }
3157
        }
3158

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

    
3185
            List<double[]> vertices = new List<double[]>();
3186
            for (int i = 1; i <= verticesCount; i++)
3187
            {
3188
                double x = 0;
3189
                double y = 0;
3190
                lineStringGeometry.GetVertex(i, ref x, ref y);
3191
                vertices.Add(new double[] { x, y });
3192
            }
3193

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

    
3210
                        placeRunInputs.AddPoint(points[0], points[1]);
3211
                    }
3212
                    else
3213
                    {
3214
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
3215
                    }
3216
                }
3217
                // 마지막 심볼이 있고 마지막 좌표일 때
3218
                else if (endSymbol != null && i == vertices.Count - 1)
3219
                {
3220
                    if (bEnd)
3221
                    {
3222
                        placeRunInputs.AddPoint(points[0], points[1]);
3223

    
3224
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
3225
                        if (slopeType == SlopeType.HORIZONTAL)
3226
                            placeRunInputs.AddPoint(points[0], -0.1);
3227
                        else if (slopeType == SlopeType.VERTICAL)
3228
                            placeRunInputs.AddPoint(-0.1, points[1]);
3229
                        else
3230
                            placeRunInputs.AddPoint(points[0], -0.1);
3231
                    }
3232
                    else
3233
                    {
3234
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3235
                    }
3236
                }
3237
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
3238
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
3239
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
3240
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
3241
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
3242
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
3243
                else
3244
                    placeRunInputs.AddPoint(points[0], points[1]);
3245
            }
3246

    
3247
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3248
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3249

    
3250
            ReleaseCOMObjects(placeRunInputs);
3251
            ReleaseCOMObjects(_LMAItem);
3252
            ReleaseCOMObjects(modelItem);
3253

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

    
3275
                if (endSymbol != null && bEnd)
3276
                {
3277
                    if (startSymbol != null)
3278
                    {
3279
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
3280
                        newConnector = dicVertices.First().Key;
3281
                    }
3282

    
3283
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
3284
                    placeRunInputs = new PlaceRunInputs();
3285
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
3286
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
3287
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3288
                    if (_LMConnector != null)
3289
                    {
3290
                        _LMConnector.Commit();
3291
                        RemoveConnectorForReModelingLine(newConnector);
3292
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
3293
                        ReleaseCOMObjects(_LMConnector);
3294
                    }
3295
                    ReleaseCOMObjects(placeRunInputs);
3296
                    ReleaseCOMObjects(_LMAItem);
3297
                }
3298

    
3299
                line.SPPID.ModelItemId = newConnector.ModelItemID;
3300
                ReleaseCOMObjects(newConnector);
3301
            }
3302

    
3303
            ReleaseCOMObjects(modelItem);
3304
        }
3305

    
3306
        /// <summary>
3307
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
3308
        /// </summary>
3309
        /// <param name="connector"></param>
3310
        private void RemoveConnectorForReModelingLine(LMConnector connector)
3311
        {
3312
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
3313
            foreach (var item in dicVertices)
3314
            {
3315
                if (item.Value.Count == 2)
3316
                {
3317
                    bool result = false;
3318
                    foreach (var point in item.Value)
3319
                    {
3320
                        if (point[0] < 0 || point[1] < 0)
3321
                        {
3322
                            result = true;
3323
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
3324
                            break;
3325
                        }
3326
                    }
3327

    
3328
                    if (result)
3329
                        break;
3330
                }
3331
            }
3332
            foreach (var item in dicVertices)
3333
                ReleaseCOMObjects(item.Key);
3334
        }
3335

    
3336
        /// <summary>
3337
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
3338
        /// </summary>
3339
        /// <param name="symbol"></param>
3340
        /// <param name="line"></param>
3341
        /// <returns></returns>
3342
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
3343
        {
3344
            LMSymbol _LMSymbol = null;
3345
            foreach (var connector in symbol.CONNECTORS)
3346
            {
3347
                if (connector.CONNECTEDITEM == line.UID)
3348
                {
3349
                    if (connector.Index == 0)
3350
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3351
                    else
3352
                    {
3353
                        ChildSymbol child = null;
3354
                        foreach (var childSymbol in symbol.ChildSymbols)
3355
                        {
3356
                            if (childSymbol.Connectors.Contains(connector))
3357
                                child = childSymbol;
3358
                            else
3359
                                child = GetChildSymbolByConnector(childSymbol, connector);
3360

    
3361
                            if (child != null)
3362
                                break;
3363
                        }
3364

    
3365
                        if (child != null)
3366
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3367
                    }
3368

    
3369
                    break;
3370
                }
3371
            }
3372

    
3373
            return _LMSymbol;
3374
        }
3375

    
3376
        /// <summary>
3377
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3378
        /// </summary>
3379
        /// <param name="item"></param>
3380
        /// <param name="connector"></param>
3381
        /// <returns></returns>
3382
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3383
        {
3384
            foreach (var childSymbol in item.ChildSymbols)
3385
            {
3386
                if (childSymbol.Connectors.Contains(connector))
3387
                    return childSymbol;
3388
                else
3389
                    return GetChildSymbolByConnector(childSymbol, connector);
3390
            }
3391

    
3392
            return null;
3393
        }
3394

    
3395
        /// <summary>
3396
        /// EndBreak 모델링 메서드
3397
        /// </summary>
3398
        /// <param name="endBreak"></param>
3399
        private void EndBreakModeling(EndBreak endBreak)
3400
        {
3401
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3402
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3403

    
3404
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3405
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3406
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3407

    
3408
            if (targetLMConnector != null)
3409
            {
3410
                // LEADER Line 검사
3411
                bool leaderLine = false;
3412
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3413
                if (symbolMapping != null)
3414
                    leaderLine = symbolMapping.LEADERLINE;
3415

    
3416
                SegmentLocation location;
3417
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3418
                Array array = null;
3419
                if (point != null)
3420
                    array = new double[] { 0, point[0], point[1] };
3421
                else
3422
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3423

    
3424
                LMLabelPersist _LmLabelPersist;
3425

    
3426
                Property property = endBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Freeze");
3427
                if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3428
                {
3429
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3430
                }
3431
                else
3432
                {
3433
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3434
                }
3435

    
3436
                if (_LmLabelPersist != null)
3437
                {
3438
                    _LmLabelPersist.Commit();
3439
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3440
                    if (_LmLabelPersist.ModelItemObject != null)
3441
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3442
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3443

    
3444
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3445

    
3446
                    // end break arrange
3447
                    if (property == null || string.IsNullOrEmpty(property.VALUE) || !property.VALUE.Equals("True"))
3448
                    {
3449
                        MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3450
                    }
3451

    
3452
                    ReleaseCOMObjects(_LmLabelPersist);
3453
                }
3454
                ReleaseCOMObjects(targetLMConnector);
3455
            }
3456
            else
3457
            {
3458
                Log.Write("End Break UID : " + endBreak.UID);
3459
                Log.Write("Can't find targetLMConnector");
3460
            }
3461
        }
3462

    
3463
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3464
        {
3465
            double x = 0, y = 0;
3466
            if (location.HasFlag(SegmentLocation.Up))
3467
                y = GridSetting.GetInstance().Length * 3;
3468
            else if (location.HasFlag(SegmentLocation.Down))
3469
                y = -GridSetting.GetInstance().Length * 3;
3470

    
3471
            if (location.HasFlag(SegmentLocation.Right))
3472
                x = GridSetting.GetInstance().Length * 3;
3473
            else if (location.HasFlag(SegmentLocation.Left))
3474
                x = -GridSetting.GetInstance().Length * 3;
3475

    
3476
            if (x != 0 || y != 0)
3477
            {
3478
                radApp.ActiveSelectSet.RemoveAll();
3479
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3480
                if (dependency != null)
3481
                {
3482
                    radApp.ActiveSelectSet.Add(dependency);
3483
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3484
                    transform.DefineByMove2d(x, y);
3485
                    radApp.ActiveSelectSet.Transform(transform, true);
3486
                    radApp.ActiveSelectSet.RemoveAll();
3487
                }
3488
            }
3489
        }
3490

    
3491
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3492
        {
3493
            string symbolPath = string.Empty;
3494
            #region get symbol path
3495
            if (string.IsNullOrEmpty(changeSymbolPath))
3496
            {
3497
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3498
                symbolPath = GetSPPIDFileName(modelItem);
3499
                ReleaseCOMObjects(modelItem);
3500
            }
3501
            else
3502
                symbolPath = changeSymbolPath;
3503

    
3504
            #endregion
3505

    
3506
            LMConnector newConnector = null;
3507
            dynamic OID = connector.get_GraphicOID().ToString();
3508
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3509
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3510
            int verticesCount = lineStringGeometry.VertexCount;
3511
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3512
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3513

    
3514
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3515
            {
3516
                double[] vertices = null;
3517
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3518
                double x = 0;
3519
                double y = 0;
3520
                lineStringGeometry.GetVertex(1, ref x, ref y);
3521

    
3522
                string flowDirection = string.Empty;
3523
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3524
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3525
                    flowDirection = flowAttribute.get_Value().ToString();
3526

    
3527
                if (flowDirection == "End 1 is downstream (Outlet)")
3528
                {
3529
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3530
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3531
                    flowDirection = "End 1 is upstream (Inlet)";
3532
                }
3533
                else
3534
                {
3535
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3536
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3537
                }
3538
                string oldModelItemId = connector.ModelItemID;
3539
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3540
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3541
                newConnector.Commit();
3542
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3543
                if (!string.IsNullOrEmpty(flowDirection))
3544
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3545
                ReleaseCOMObjects(connector);
3546

    
3547
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3548
                {
3549
                    foreach (var repId in line.SPPID.Representations)
3550
                    {
3551
                        LMConnector _connector = dataSource.GetConnector(repId);
3552
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3553
                        {
3554
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3555
                            {
3556
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3557
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3558
                            }
3559
                        }
3560
                        ReleaseCOMObjects(_connector);
3561
                        _connector = null;
3562
                    }
3563
                }
3564
            }
3565

    
3566
            return newConnector;
3567
        }
3568

    
3569
        /// <summary>
3570
        /// SpecBreak Modeling 메서드
3571
        /// </summary>
3572
        /// <param name="specBreak"></param>
3573
        private void SpecBreakModeling(SpecBreak specBreak)
3574
        {
3575
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3576
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3577

    
3578
            if (upStreamObj != null &&
3579
                downStreamObj != null)
3580
            {
3581
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3582
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) &&
3583
                    targetLMConnector != null &&
3584
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3585
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3586

    
3587
                if (targetLMConnector != null)
3588
                {
3589
                    foreach (var attribute in specBreak.ATTRIBUTES)
3590
                    {
3591
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3592
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3593
                        {
3594
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3595
                            SegmentLocation location;
3596
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3597
                            Array array = null;
3598
                            if (point != null)
3599
                                array = new double[] { 0, point[0], point[1] };
3600
                            else
3601
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3602
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3603

    
3604
                            if (_LmLabelPersist != null)
3605
                            {
3606
                                _LmLabelPersist.Commit();
3607
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3608
                                if (_LmLabelPersist.ModelItemObject != null)
3609
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3610
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3611

    
3612
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3613

    
3614
                                // spec break arrange
3615
                                MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3616

    
3617
                                ReleaseCOMObjects(_LmLabelPersist);
3618
                            }
3619
                        }
3620
                    }
3621

    
3622
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3623
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3624
                    {
3625
                        // temp
3626
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3627
                    }
3628
                    ReleaseCOMObjects(targetLMConnector);
3629
                }
3630
                else
3631
                {
3632
                    Log.Write("Spec Break UID : " + specBreak.UID);
3633
                    Log.Write("Can't find targetLMConnector");
3634
                }
3635
            }
3636
        }
3637

    
3638
        private bool IsRhombus(LMLabelPersist labelPersist, out double x, out double y, out double radius)
3639
        {
3640
            bool result = false;
3641
            x = 0; y = 0; radius = 0;
3642

    
3643
            string oid = labelPersist.get_GraphicOID().ToString();
3644
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3645

    
3646
            if (dependency != null)
3647
            {
3648
                bool isLabel = false;
3649
                foreach (var attributes in dependency.AttributeSets)
3650
                {
3651
                    foreach (var attribute in attributes)
3652
                    {
3653
                        string name = attribute.Name;
3654
                        string value = attribute.GetValue().ToString();
3655
                        if (name == "DrawingItemType" && value == "LabelPersist")
3656
                        {
3657
                            isLabel = true;
3658
                            break;
3659
                        }
3660
                    }
3661
                }
3662
                if (isLabel)
3663
                {
3664
                    double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
3665
                    foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
3666
                    {
3667
                        if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLine2d)
3668
                        {
3669
                            Ingr.RAD2D.Line2d line2D = drawingObject as Ingr.RAD2D.Line2d;
3670

    
3671
                            double x1, y1, x2, y2;
3672
                            line2D.GetStartPoint(out x1, out y1);
3673
                            line2D.GetEndPoint(out x2, out y2);
3674
                            double tX1 = Math.Min(x1, x2), tY1 = Math.Min(y1, y2), tX2 = Math.Max(x1, x2), tY2 = Math.Max(y1, y2);
3675
                            if (minX > tX1)
3676
                                minX = tX1;
3677
                            if (minY > tY1)
3678
                                minY = tY1;
3679
                            if (maxX < tX2)
3680
                                maxX = tX2;
3681
                            if (maxY < tY2)
3682
                                maxY = tY2;
3683
                        }
3684
                    }
3685

    
3686
                    double width = Math.Abs(maxX - minX);
3687
                    double height = Math.Abs(maxY - minY);
3688
                    double ratio = width / height * 100;
3689
                    if (ratio > 99d && ratio < 101d)
3690
                    {
3691
                        result = true;
3692
                    }
3693
                    x = (maxX + minX) / 2d;
3694
                    y = (maxY + minY) / 2d;
3695
                    radius = width / 2d;
3696
                }
3697
            }
3698

    
3699
            return result;
3700
        }
3701

    
3702
        private void MoveSegmentBreak(string connectorID, LMLabelPersist labelPersist)
3703
        {
3704
            bool bFind = false;
3705
            double x, y, radius;
3706
            if (IsRhombus(labelPersist, out x, out y, out radius))
3707
            {
3708
                List<double[]> itemPoints = new List<double[]>();
3709
                LMConnector connector = dataSource.GetConnector(connectorID);
3710
                foreach (LMLabelPersist label in connector.LabelPersists)
3711
                {
3712
                    if (!"Active".Equals(label.get_ItemStatus()))
3713
                        continue;
3714

    
3715
                    if (!label.Id.Equals(labelPersist.Id))
3716
                    {
3717
                        double centerX, centerY, temp;
3718
                        if (IsRhombus(label, out centerX, out centerY, out temp))
3719
                        {
3720
                            bFind = true;
3721
                            itemPoints.Add(new double[] { centerX, centerY });
3722
                        }
3723
                    }
3724
                }
3725
                ReleaseCOMObjects(connector);
3726

    
3727

    
3728
                if (bFind)
3729
                {
3730
                    double[] startPoint = itemPoints.First();
3731
                    itemPoints.RemoveAt(0);
3732

    
3733
                    for (int i = 0; i < 8; i++)
3734
                    {
3735
                        double pointX = 0, pointY = 0;
3736
                        switch (i)
3737
                        {
3738
                            case 0:
3739
                                pointX = startPoint[0] + radius;
3740
                                pointY = startPoint[1] + radius;
3741
                                break;
3742
                            case 1:
3743
                                pointX = startPoint[0] + radius + radius;
3744
                                pointY = startPoint[1];
3745
                                break;
3746
                            case 2:
3747
                                pointX = startPoint[0] + radius;
3748
                                pointY = startPoint[1] - radius;
3749
                                break;
3750
                            case 3:
3751
                                pointX = startPoint[0];
3752
                                pointY = startPoint[1] - radius - radius;
3753
                                break;
3754
                            case 4:
3755
                                pointX = startPoint[0] - radius;
3756
                                pointY = startPoint[1] - radius;
3757
                                break;
3758
                            case 5:
3759
                                pointX = startPoint[0] - radius - radius;
3760
                                pointY = startPoint[1];
3761
                                break;
3762
                            case 6:
3763
                                pointX = startPoint[0] - radius;
3764
                                pointY = startPoint[1] + radius;
3765
                                break;
3766
                            case 7:
3767
                                pointX = startPoint[0];
3768
                                pointY = startPoint[1] + radius + radius;
3769
                                break;
3770
                            default:
3771
                                break;
3772
                        }
3773

    
3774
                        if (!ExistSegmentByPoint(pointX, pointY))
3775
                        {
3776
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
3777
                            if (dependency != null)
3778
                            {
3779
                                radApp.ActiveSelectSet.RemoveAll();
3780
                                radApp.ActiveSelectSet.Add(dependency);
3781
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3782
                                transform.DefineByMove2d(pointX - x, pointY - y);
3783
                                radApp.ActiveSelectSet.Transform(transform, true);
3784
                                radApp.ActiveSelectSet.RemoveAll();
3785
                            }
3786
                            break;
3787
                        }
3788
                    }
3789

    
3790
                    bool ExistSegmentByPoint(double pointX, double pointY)
3791
                    {
3792
                        bool result = false;
3793
                        foreach (var item in itemPoints)
3794
                        {
3795
                            double distance = SPPIDUtil.CalcPointToPointdDistance(item[0], item[1], pointX, pointY);
3796
                            if (Math.Truncate(distance * 1000000000d).Equals(0))
3797
                                result = true;
3798
                        }
3799
                        return result;
3800
                    }
3801
                }
3802
            }
3803

    
3804
            if (!bFind)
3805
                MoveSegmentBestLocation(labelPersist.get_GraphicOID().ToString(), new double[] { x - radius, y - radius, x + radius, y + radius }, itemRange);
3806
        }
3807

    
3808
        LMConnectors GetConnectors()
3809
        {
3810
            LMAFilter filter = new LMAFilter();
3811
            LMACriterion criterion1 = new LMACriterion();
3812
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3813
            criterion1.Operator = "=";
3814
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3815
            criterion1.Conjunctive = true;
3816
            filter.get_Criteria().Add(criterion1);
3817
            filter.ItemType = "Connector";
3818

    
3819
            LMACriterion criterion2 = new LMACriterion();
3820
            criterion2.SourceAttributeName = "ITEMSTATUS";
3821
            criterion2.Operator = "=";
3822
            criterion2.set_ValueAttribute("1");
3823
            criterion2.Conjunctive = true;
3824
            filter.get_Criteria().Add(criterion2);
3825

    
3826
            LMACriterion criterion3 = new LMACriterion();
3827
            criterion3.SourceAttributeName = "INSTOCKPILE";
3828
            criterion3.Operator = "=";
3829
            criterion3.set_ValueAttribute("1");
3830
            criterion3.Conjunctive = true;
3831
            filter.get_Criteria().Add(criterion3);
3832

    
3833
            LMConnectors items = new LMConnectors();
3834
            items.Collect(dataSource, Filter: filter);
3835

    
3836
            ReleaseCOMObjects(filter);
3837
            ReleaseCOMObjects(criterion1);
3838
            ReleaseCOMObjects(criterion2);
3839
            ReleaseCOMObjects(criterion3);
3840

    
3841
            return items;
3842
        }
3843
        LMSymbols GetSymbols()
3844
        {
3845
            LMAFilter filter = new LMAFilter();
3846
            LMACriterion criterion1 = new LMACriterion();
3847
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3848
            criterion1.Operator = "=";
3849
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3850
            criterion1.Conjunctive = true;
3851
            filter.get_Criteria().Add(criterion1);
3852
            filter.ItemType = "Symbol";
3853

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

    
3861
            LMACriterion criterion3 = new LMACriterion();
3862
            criterion3.SourceAttributeName = "INSTOCKPILE";
3863
            criterion3.Operator = "=";
3864
            criterion3.set_ValueAttribute("1");
3865
            criterion3.Conjunctive = true;
3866
            filter.get_Criteria().Add(criterion3);
3867

    
3868
            LMSymbols items = new LMSymbols();
3869
            items.Collect(dataSource, Filter: filter);
3870

    
3871
            ReleaseCOMObjects(filter);
3872
            ReleaseCOMObjects(criterion1);
3873
            ReleaseCOMObjects(criterion2);
3874
            ReleaseCOMObjects(criterion3);
3875

    
3876
            return items;
3877
        }
3878

    
3879
        private void SetConnectorAndSymbolRange()
3880
        {
3881
            itemRange = new List<double[]>();
3882

    
3883
            LMConnectors connectors = GetConnectors();
3884
            foreach (LMConnector connector in connectors)
3885
            {
3886
                List<double[]> vertices = GetConnectorVertices(connector);
3887
                for (int i = 0; i < vertices.Count - 1; i++)
3888
                {
3889
                    double[] point1 = vertices[i];
3890
                    double[] point2 = vertices[i + 1];
3891
                    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]);
3892
                    double gap = 0.0001d;
3893
                    itemRange.Add(new double[] { x1 - gap, y1 - gap, x2 + gap, y2 + gap });
3894
                }
3895
                ReleaseCOMObjects(connector);
3896
            }
3897
            ReleaseCOMObjects(connectors);
3898

    
3899
            LMSymbols symbols = GetSymbols();
3900
            foreach (LMSymbol symbol in symbols)
3901
            {
3902
                string oid = symbol.get_GraphicOID().ToString();
3903
                DrawingObjectBase drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid];
3904
                if (drawingObject != null)
3905
                {
3906
                    double x1, y1, x2, y2;
3907
                    drawingObject.Range(out x1, out y1, out x2, out y2);
3908
                    itemRange.Add(new double[] { x1, y1, x2, y2 });
3909
                }
3910

    
3911
                ReleaseCOMObjects(symbol);
3912
            }
3913
            ReleaseCOMObjects(symbols);
3914
        }
3915

    
3916
        private void MoveSegmentBestLocation(string oid, double[] segmentRange, List<double[]> allRanges)
3917
        {
3918
            double minValue = Math.Min(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3919
            double maxValue = Math.Max(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3920

    
3921
            double maxX = 0, maxY = 0;
3922
            maxX = maxValue * 10;
3923
            maxY = minValue * 10;
3924

    
3925
            double move = minValue / 10d;
3926
            double textGap = minValue / 3d;
3927
            segmentRange = new double[] { segmentRange[0] - textGap, segmentRange[1] - textGap, segmentRange[2] + textGap, segmentRange[3] + textGap };
3928

    
3929

    
3930
            List<double[]> containRanges = new List<double[]>();
3931
            double[] findRange = new double[] {
3932
            segmentRange[0] - maxX, segmentRange[1] - maxY,
3933
            segmentRange[2] + maxX, segmentRange[3] + maxY};
3934

    
3935
            foreach (var range in allRanges)
3936
                if (SPPIDUtil.IsOverlap(findRange, range))
3937
                    containRanges.Add(range);
3938

    
3939
            double movePointX = 0, movePointY = 0, distance = double.MaxValue;
3940
            for (double x = 0; x < maxX; x = x + move)
3941
                for (double y = 0; y < maxY; y = y + move)
3942
                    for (int i = 0; i < 4; i++)
3943
                    {
3944
                        double tempX = 0d, tempY = 0d;
3945
                        switch (i)
3946
                        {
3947
                            case 0:
3948
                                tempX = x;
3949
                                tempY = y;
3950
                                break;
3951
                            case 1:
3952
                                tempX = -x;
3953
                                tempY = y;
3954
                                break;
3955
                            case 2:
3956
                                tempX = -x;
3957
                                tempY = -y;
3958
                                break;
3959
                            case 3:
3960
                                tempX = x;
3961
                                tempY = -y;
3962
                                break;
3963
                            default:
3964
                                break;
3965
                        }
3966

    
3967
                        bool result = true;
3968
                        double[] movedRange = new double[] { segmentRange[0] + tempX, segmentRange[1] + tempY, segmentRange[2] + tempX, segmentRange[3] + tempY };
3969
                        foreach (double[] range in containRanges)
3970
                        {
3971
                            if (SPPIDUtil.IsOverlap(range, movedRange))
3972
                            {
3973
                                result = false;
3974
                                break;
3975
                            }
3976
                        }
3977

    
3978
                        if (result)
3979
                        {
3980
                            //double tempDistance = Utils.CalcDistance(new double[] { 0, 0, 0 }, new double[] { tempX, tempY, 0 });
3981
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(0, 0, tempX, tempY);
3982
                            bool bChange = false;
3983
                            if (distance > tempDistance)
3984
                                bChange = true;
3985
                            else if (distance.Equals(tempDistance) && (movePointX.Equals(0d) || movePointY.Equals(0d)))
3986
                                bChange = true;
3987

    
3988
                            if (bChange)
3989
                            {
3990
                                distance = tempDistance;
3991
                                movePointX = tempX;
3992
                                movePointY = tempY;
3993
                            }
3994
                        }
3995
                    }
3996

    
3997
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3998
            if (dependency != null)
3999
            {
4000
                radApp.ActiveSelectSet.RemoveAll();
4001
                radApp.ActiveSelectSet.Add(dependency);
4002
                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4003
                transform.DefineByMove2d(movePointX, movePointY);
4004
                radApp.ActiveSelectSet.Transform(transform, true);
4005
                radApp.ActiveSelectSet.RemoveAll();
4006
            }
4007
        }
4008

    
4009
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
4010
        {
4011
            LMConnector targetConnector = null;
4012
            Symbol targetSymbol = targetObj as Symbol;
4013
            Symbol connectedSymbol = connectedObj as Symbol;
4014
            Line targetLine = targetObj as Line;
4015
            Line connectedLine = connectedObj as Line;
4016
            if (targetSymbol != null && connectedSymbol != null)
4017
            {
4018
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4019
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4020

    
4021
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
4022
                {
4023
                    if (connector.get_ItemStatus() != "Active")
4024
                        continue;
4025

    
4026
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
4027
                    {
4028
                        targetConnector = connector;
4029
                        break;
4030
                    }
4031
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
4032
                    {
4033
                        targetConnector = connector;
4034
                        break;
4035
                    }
4036
                }
4037

    
4038
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
4039
                {
4040
                    if (connector.get_ItemStatus() != "Active")
4041
                        continue;
4042

    
4043
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
4044
                    {
4045
                        targetConnector = connector;
4046
                        break;
4047
                    }
4048
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
4049
                    {
4050
                        targetConnector = connector;
4051
                        break;
4052
                    }
4053
                }
4054

    
4055
                ReleaseCOMObjects(targetLMSymbol);
4056
                ReleaseCOMObjects(connectedLMSymbol);
4057
            }
4058
            else if (targetLine != null && connectedLine != null)
4059
            {
4060
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4061
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4062

    
4063
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
4064
                {
4065
                    foreach (LMRepresentation rep in targetModelItem.Representations)
4066
                    {
4067
                        if (targetConnector != null)
4068
                            break;
4069

    
4070
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4071
                        {
4072
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4073

    
4074
                            if (IsConnected(_LMConnector, connectedModelItem))
4075
                                targetConnector = _LMConnector;
4076
                            else
4077
                                ReleaseCOMObjects(_LMConnector);
4078
                        }
4079
                    }
4080

    
4081
                    ReleaseCOMObjects(targetModelItem);
4082
                }
4083
            }
4084
            else
4085
            {
4086
                LMSymbol connectedLMSymbol = null;
4087
                if (connectedSymbol != null)
4088
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4089
                else if (targetSymbol != null)
4090
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4091
                else
4092
                {
4093

    
4094
                }
4095
                LMModelItem targetModelItem = null;
4096
                if (targetLine != null)
4097
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4098
                else if (connectedLine != null)
4099
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4100
                else
4101
                {
4102

    
4103
                }
4104
                if (connectedLMSymbol != null && targetModelItem != null)
4105
                {
4106
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
4107
                    {
4108
                        if (connector.get_ItemStatus() != "Active")
4109
                            continue;
4110

    
4111
                        if (IsConnected(connector, targetModelItem))
4112
                        {
4113
                            targetConnector = connector;
4114
                            break;
4115
                        }
4116
                    }
4117

    
4118
                    if (targetConnector == null)
4119
                    {
4120
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
4121
                        {
4122
                            if (connector.get_ItemStatus() != "Active")
4123
                                continue;
4124

    
4125
                            if (IsConnected(connector, targetModelItem))
4126
                            {
4127
                                targetConnector = connector;
4128
                                break;
4129
                            }
4130
                        }
4131
                    }
4132
                }
4133

    
4134
            }
4135

    
4136
            return targetConnector;
4137
        }
4138

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

    
4186
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
4187

    
4188
                    ReleaseCOMObjects(modelItem);
4189
                    ReleaseCOMObjects(connectedConnector);
4190

    
4191
                    if (vertices.Count > 0)
4192
                    {
4193
                        if (connIndex == 1)
4194
                            result = vertices[0];
4195
                        else if (connIndex == 2)
4196
                            result = vertices[vertices.Count - 1];
4197

    
4198
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4199
                        {
4200
                            result = new double[] { result[0], result[1] };
4201
                            location = SegmentLocation.Up;
4202
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4203
                                location = location | SegmentLocation.Right;
4204
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4205
                                location = location | SegmentLocation.Left;
4206
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4207
                                location = location | SegmentLocation.Left;
4208
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4209
                                location = location | SegmentLocation.Right;
4210
                        }
4211
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
4212
                        {
4213
                            result = new double[] { result[0], result[1] };
4214
                            location = SegmentLocation.Right;
4215
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4216
                                location = location | SegmentLocation.Up;
4217
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4218
                                location = location | SegmentLocation.Down;
4219
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4220
                                location = location | SegmentLocation.Down;
4221
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4222
                                location = location | SegmentLocation.Up;
4223
                        }
4224

    
4225
                    }
4226
                }
4227
                else
4228
                {
4229
                    Log.Write("error in GetSegemtPoint");
4230
                }
4231
            }
4232

    
4233
            return result;
4234
        }
4235

    
4236
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
4237
        {
4238
            bool result = false;
4239

    
4240
            foreach (LMRepresentation rep in modelItem.Representations)
4241
            {
4242
                if (result)
4243
                    break;
4244

    
4245
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4246
                {
4247
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4248

    
4249
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4250
                        connector.ConnectItem1SymbolObject != null &&
4251
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4252
                    {
4253
                        result = true;
4254
                        ReleaseCOMObjects(_LMConnector);
4255
                        break;
4256
                    }
4257
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4258
                        connector.ConnectItem2SymbolObject != null &&
4259
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4260
                    {
4261
                        result = true;
4262
                        ReleaseCOMObjects(_LMConnector);
4263
                        break;
4264
                    }
4265
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4266
                        connector.ConnectItem1SymbolObject != null &&
4267
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4268
                    {
4269
                        result = true;
4270
                        ReleaseCOMObjects(_LMConnector);
4271
                        break;
4272
                    }
4273
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4274
                        connector.ConnectItem2SymbolObject != null &&
4275
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4276
                    {
4277
                        result = true;
4278
                        ReleaseCOMObjects(_LMConnector);
4279
                        break;
4280
                    }
4281

    
4282
                    ReleaseCOMObjects(_LMConnector);
4283
                }
4284
            }
4285

    
4286

    
4287
            return result;
4288
        }
4289

    
4290
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
4291
        {
4292
            foreach (LMRepresentation rep in modelItem.Representations)
4293
            {
4294
                if (connectedConnector != null)
4295
                    break;
4296

    
4297
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4298
                {
4299
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4300

    
4301
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4302
                        connector.ConnectItem1SymbolObject != null &&
4303
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4304
                    {
4305
                        connectedConnector = _LMConnector;
4306
                        connectorIndex = 1;
4307
                        break;
4308
                    }
4309
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4310
                        connector.ConnectItem2SymbolObject != null &&
4311
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4312
                    {
4313
                        connectedConnector = _LMConnector;
4314
                        connectorIndex = 2;
4315
                        break;
4316
                    }
4317
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4318
                        connector.ConnectItem1SymbolObject != null &&
4319
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4320
                    {
4321
                        connectedConnector = _LMConnector;
4322
                        connectorIndex = 1;
4323
                        break;
4324
                    }
4325
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4326
                        connector.ConnectItem2SymbolObject != null &&
4327
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4328
                    {
4329
                        connectedConnector = _LMConnector;
4330
                        connectorIndex = 2;
4331
                        break;
4332
                    }
4333

    
4334
                    if (connectedConnector == null)
4335
                        ReleaseCOMObjects(_LMConnector);
4336
                }
4337
            }
4338
        }
4339

    
4340
        /// <summary>
4341
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
4342
        /// </summary>
4343
        /// <param name="modelItemID1"></param>
4344
        /// <param name="modelItemID2"></param>
4345
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
4346
        {
4347
            try
4348
            {
4349
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
4350
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
4351
                List<double[]> vertices1 = null;
4352
                string graphicOID1 = string.Empty;
4353
                if (connector1 != null)
4354
                {
4355
                    vertices1 = GetConnectorVertices(connector1);
4356
                    graphicOID1 = connector1.get_GraphicOID();
4357
                }
4358
                _LMAItem item1 = modelItem1.AsLMAItem();
4359
                ReleaseCOMObjects(connector1);
4360
                connector1 = null;
4361

    
4362
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
4363
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
4364
                List<double[]> vertices2 = null;
4365
                string graphicOID2 = string.Empty;
4366
                if (connector2 != null)
4367
                {
4368
                    vertices2 = GetConnectorVertices(connector2);
4369
                    graphicOID2 = connector2.get_GraphicOID();
4370
                }
4371
                _LMAItem item2 = modelItem2.AsLMAItem();
4372
                ReleaseCOMObjects(connector2);
4373
                connector2 = null;
4374

    
4375
                // item2가 item1으로 조인
4376
                _placement.PIDJoinRuns(ref item1, ref item2);
4377
                item1.Commit();
4378
                item2.Commit();
4379

    
4380
                string beforeID = string.Empty;
4381
                string afterID = string.Empty;
4382

    
4383
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
4384
                {
4385
                    beforeID = modelItem2.Id;
4386
                    afterID = modelItem1.Id;
4387
                    survivorId = afterID;
4388
                }
4389
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
4390
                {
4391
                    beforeID = modelItem1.Id;
4392
                    afterID = modelItem2.Id;
4393
                    survivorId = afterID;
4394
                }
4395
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
4396
                {
4397
                    int model1Cnt = GetConnectorCount(modelId1);
4398
                    int model2Cnt = GetConnectorCount(modelId2);
4399
                    if (model1Cnt == 0)
4400
                    {
4401
                        beforeID = modelItem1.Id;
4402
                        afterID = modelItem2.Id;
4403
                        survivorId = afterID;
4404
                    }
4405
                    else if (model2Cnt == 0)
4406
                    {
4407
                        beforeID = modelItem2.Id;
4408
                        afterID = modelItem1.Id;
4409
                        survivorId = afterID;
4410
                    }
4411
                    else
4412
                        survivorId = null;
4413
                }
4414
                else
4415
                {
4416
                    Log.Write("잘못된 경우");
4417
                    survivorId = null;
4418
                }
4419

    
4420
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
4421
                {
4422
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
4423
                    foreach (var line in lines)
4424
                        line.SPPID.ModelItemId = afterID;
4425
                }
4426

    
4427
                ReleaseCOMObjects(modelItem1);
4428
                ReleaseCOMObjects(item1);
4429
                ReleaseCOMObjects(modelItem2);
4430
                ReleaseCOMObjects(item2);
4431
            }
4432
            catch (Exception ex)
4433
            {
4434
                Log.Write("Join Error");
4435
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
4436
            }
4437
        }
4438
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
4439
        {
4440
            bool result = false;
4441
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
4442
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
4443
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
4444

    
4445
            foreach (var item in endBreaks)
4446
            {
4447
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
4448
                {
4449
                    result = true;
4450
                    break;
4451
                }
4452
            }
4453

    
4454
            return result;
4455
        }
4456
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
4457
        {
4458
            List<string> temp = new List<string>();
4459
            List<LMConnector> connectors = new List<LMConnector>();
4460
            foreach (LMConnector connector in symbol.Avoid1Connectors)
4461
            {
4462
                if (connector.get_ItemStatus() != "Active")
4463
                    continue;
4464

    
4465
                LMModelItem modelItem = connector.ModelItemObject;
4466
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4467
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4468
                    temp.Add(modelItem.Id);
4469

    
4470
                if (temp.Contains(modelItem.Id) &&
4471
                    connOtherSymbol != null &&
4472
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4473
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4474
                    temp.Remove(modelItem.Id);
4475

    
4476

    
4477
                if (temp.Contains(modelItem.Id))
4478
                    connectors.Add(connector);
4479
                ReleaseCOMObjects(connOtherSymbol);
4480
                connOtherSymbol = null;
4481
                ReleaseCOMObjects(modelItem);
4482
                modelItem = null;
4483
            }
4484

    
4485
            foreach (LMConnector connector in symbol.Avoid2Connectors)
4486
            {
4487
                if (connector.get_ItemStatus() != "Active")
4488
                    continue;
4489

    
4490
                LMModelItem modelItem = connector.ModelItemObject;
4491
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4492
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4493
                    temp.Add(modelItem.Id);
4494

    
4495
                if (temp.Contains(modelItem.Id) &&
4496
                    connOtherSymbol != null &&
4497
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4498
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4499
                    temp.Remove(modelItem.Id);
4500

    
4501
                if (temp.Contains(modelItem.Id))
4502
                    connectors.Add(connector);
4503
                ReleaseCOMObjects(connOtherSymbol);
4504
                connOtherSymbol = null;
4505
                ReleaseCOMObjects(modelItem);
4506
                modelItem = null;
4507
            }
4508

    
4509

    
4510
            List<string> result = new List<string>();
4511
            string originalName = GetSPPIDFileName(modelId);
4512
            foreach (var connector in connectors)
4513
            {
4514
                string fileName = GetSPPIDFileName(connector.ModelItemID);
4515
                if (originalName == fileName)
4516
                    result.Add(connector.ModelItemID);
4517
                else
4518
                {
4519
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
4520
                        result.Add(connector.ModelItemID);
4521
                    else
4522
                    {
4523
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
4524
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
4525
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
4526
                            result.Add(connector.ModelItemID);
4527
                    }
4528
                }
4529
            }
4530

    
4531
            foreach (var connector in connectors)
4532
                ReleaseCOMObjects(connector);
4533

    
4534
            return result;
4535

    
4536

    
4537
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
4538
            {
4539
                LMSymbol findResult = null;
4540
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
4541
                    findResult = connector.ConnectItem1SymbolObject;
4542
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
4543
                    findResult = connector.ConnectItem2SymbolObject;
4544

    
4545
                return findResult;
4546
            }
4547
        }
4548

    
4549
        /// <summary>
4550
        /// PipeRun의 좌표를 가져오는 메서드
4551
        /// </summary>
4552
        /// <param name="modelId"></param>
4553
        /// <returns></returns>
4554
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
4555
        {
4556
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
4557
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
4558

    
4559
            if (modelItem != null)
4560
            {
4561
                foreach (LMRepresentation rep in modelItem.Representations)
4562
                {
4563
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4564
                    {
4565
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4566
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
4567
                        {
4568
                            ReleaseCOMObjects(_LMConnector);
4569
                            _LMConnector = null;
4570
                            continue;
4571
                        }
4572
                        connectorVertices.Add(_LMConnector, new List<double[]>());
4573
                        dynamic OID = rep.get_GraphicOID().ToString();
4574
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4575
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4576
                        int verticesCount = lineStringGeometry.VertexCount;
4577
                        double[] vertices = null;
4578
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
4579
                        for (int i = 0; i < verticesCount; i++)
4580
                        {
4581
                            double x = 0;
4582
                            double y = 0;
4583
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4584
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
4585
                        }
4586
                    }
4587
                }
4588

    
4589
                ReleaseCOMObjects(modelItem);
4590
            }
4591

    
4592
            return connectorVertices;
4593
        }
4594

    
4595
        private List<double[]> GetConnectorVertices(LMConnector connector)
4596
        {
4597
            List<double[]> vertices = new List<double[]>();
4598
            if (connector != null)
4599
            {
4600
                dynamic OID = connector.get_GraphicOID().ToString();
4601
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4602
                if (drawingObject != null)
4603
                {
4604
                    Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4605
                    int verticesCount = lineStringGeometry.VertexCount;
4606
                    double[] value = null;
4607
                    lineStringGeometry.GetVertices(ref verticesCount, ref value);
4608
                    for (int i = 0; i < verticesCount; i++)
4609
                    {
4610
                        double x = 0;
4611
                        double y = 0;
4612
                        lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4613
                        vertices.Add(new double[] { x, y });
4614
                    }
4615
                }
4616
            }
4617
            return vertices;
4618
        }
4619

    
4620
        private double GetConnectorDistance(LMConnector connector)
4621
        {
4622
            double result = 0;
4623
            List<double[]> vertices = new List<double[]>();
4624
            if (connector != null)
4625
            {
4626
                dynamic OID = connector.get_GraphicOID().ToString();
4627
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4628
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4629
                int verticesCount = lineStringGeometry.VertexCount;
4630
                double[] value = null;
4631
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4632
                for (int i = 0; i < verticesCount; i++)
4633
                {
4634
                    double x = 0;
4635
                    double y = 0;
4636
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4637
                    vertices.Add(new double[] { x, y });
4638
                    if (vertices.Count > 1)
4639
                    {
4640
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
4641
                    }
4642
                }
4643
            }
4644
            return result;
4645
        }
4646
        private double[] GetConnectorRange(LMConnector connector)
4647
        {
4648
            double[] result = null;
4649
            List<double[]> vertices = new List<double[]>();
4650
            if (connector != null)
4651
            {
4652
                dynamic OID = connector.get_GraphicOID().ToString();
4653
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4654
                double minX = 0;
4655
                double minY = 0;
4656
                double maxX = 0;
4657
                double maxY = 0;
4658

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

    
4708
                    if ((x1 <= connX && x2 >= connX) ||
4709
                        (y1 <= connY && y2 >= connY))
4710
                    {
4711
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
4712
                        if (length >= distance)
4713
                        {
4714
                            targetConnector = item.Key;
4715
                            length = distance;
4716
                        }
4717

    
4718
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
4719
                        if (length >= distance)
4720
                        {
4721
                            targetConnector = item.Key;
4722
                            length = distance;
4723
                        }
4724
                    }
4725
                }
4726
            }
4727

    
4728
            // 못찾았을때.
4729
            length = double.MaxValue;
4730
            if (targetConnector == null)
4731
            {
4732
                foreach (var item in connectorVertices)
4733
                {
4734
                    List<double[]> points = item.Value;
4735

    
4736
                    foreach (double[] point in points)
4737
                    {
4738
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
4739
                        if (length >= distance)
4740
                        {
4741
                            targetConnector = item.Key;
4742
                            length = distance;
4743
                        }
4744
                    }
4745
                }
4746
            }
4747

    
4748
            return targetConnector;
4749
        }
4750

    
4751
        private LMConnector FindTargetLMConnectorForBranch(Line currentLine, Line targetLine, ref double x, ref double y)
4752
        {
4753
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4754
            if (vertices.Count == 0)
4755
                return null;
4756

    
4757
            double length = double.MaxValue;
4758
            LMConnector targetConnector = null;
4759
            double[] resultPoint = null;
4760
            List<double[]> targetVertices = null;
4761

    
4762
            // Vertices 포인트에 제일 가까운곳
4763
            foreach (var item in vertices)
4764
            {
4765
                List<double[]> points = item.Value;
4766
                for (int i = 0; i < points.Count; i++)
4767
                {
4768
                    double[] point = points[i];
4769
                    double tempX = point[0];
4770
                    double tempY = point[1];
4771

    
4772
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4773
                    if (length >= distance)
4774
                    {
4775
                        targetConnector = item.Key;
4776
                        length = distance;
4777
                        resultPoint = point;
4778
                        targetVertices = item.Value;
4779
                    }
4780
                }
4781
            }
4782

    
4783
            // Vertices Cross에 제일 가까운곳
4784
            foreach (var item in vertices)
4785
            {
4786
                List<double[]> points = item.Value;
4787
                for (int i = 0; i < points.Count - 1; i++)
4788
                {
4789
                    double[] point1 = points[i];
4790
                    double[] point2 = points[i + 1];
4791

    
4792
                    double maxLineX = Math.Max(point1[0], point2[0]);
4793
                    double minLineX = Math.Min(point1[0], point2[0]);
4794
                    double maxLineY = Math.Max(point1[1], point2[1]);
4795
                    double minLineY = Math.Min(point1[1], point2[1]);
4796

    
4797
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4798

    
4799
                    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]);
4800
                    if (crossingPoint != null)
4801
                    {
4802
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4803
                        if (length >= distance)
4804
                        {
4805
                            if (slope == SlopeType.Slope &&
4806
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4807
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4808
                            {
4809
                                targetConnector = item.Key;
4810
                                length = distance;
4811
                                resultPoint = crossingPoint;
4812
                                targetVertices = item.Value;
4813
                            }
4814
                            else if (slope == SlopeType.HORIZONTAL &&
4815
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4816
                            {
4817
                                targetConnector = item.Key;
4818
                                length = distance;
4819
                                resultPoint = crossingPoint;
4820
                                targetVertices = item.Value;
4821
                            }
4822
                            else if (slope == SlopeType.VERTICAL &&
4823
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4824
                            {
4825
                                targetConnector = item.Key;
4826
                                length = distance;
4827
                                resultPoint = crossingPoint;
4828
                                targetVertices = item.Value;
4829
                            }
4830
                        }
4831
                    }
4832
                }
4833
            }
4834

    
4835
            foreach (var item in vertices)
4836
                if (item.Key != null && item.Key != targetConnector)
4837
                    ReleaseCOMObjects(item.Key);
4838

    
4839
            if (SPPIDUtil.IsBranchLine(currentLine, targetLine))
4840
            {
4841
                double tempResultX = resultPoint[0];
4842
                double tempResultY = resultPoint[1];
4843
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4844

    
4845
                GridSetting gridSetting = GridSetting.GetInstance();
4846
                for (int i = 0; i < targetVertices.Count; i++)
4847
                {
4848
                    double[] point = targetVertices[i];
4849
                    double tempX = targetVertices[i][0];
4850
                    double tempY = targetVertices[i][1];
4851
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4852
                    if (tempX == tempResultX && tempY == tempResultY)
4853
                    {
4854
                        if (i == 0)
4855
                        {
4856
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4857
                            bool containZeroLength = false;
4858
                            if (connSymbol != null)
4859
                            {
4860
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4861
                                {
4862
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4863
                                        containZeroLength = true;
4864
                                }
4865
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4866
                                {
4867
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4868
                                        containZeroLength = true;
4869
                                }
4870
                            }
4871

    
4872
                            if (connSymbol == null ||
4873
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4874
                                containZeroLength)
4875
                            {
4876
                                bool bCalcX = false;
4877
                                bool bCalcY = false;
4878
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4879
                                    bCalcX = true;
4880
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4881
                                    bCalcY = true;
4882
                                else
4883
                                {
4884
                                    bCalcX = true;
4885
                                    bCalcY = true;
4886
                                }
4887

    
4888
                                if (bCalcX)
4889
                                {
4890
                                    double nextX = targetVertices[i + 1][0];
4891
                                    double newX = 0;
4892
                                    if (nextX > tempX)
4893
                                    {
4894
                                        newX = tempX + gridSetting.Length;
4895
                                        if (newX > nextX)
4896
                                            newX = (point[0] + nextX) / 2;
4897
                                    }
4898
                                    else
4899
                                    {
4900
                                        newX = tempX - gridSetting.Length;
4901
                                        if (newX < nextX)
4902
                                            newX = (point[0] + nextX) / 2;
4903
                                    }
4904
                                    resultPoint = new double[] { newX, resultPoint[1] };
4905
                                }
4906

    
4907
                                if (bCalcY)
4908
                                {
4909
                                    double nextY = targetVertices[i + 1][1];
4910
                                    double newY = 0;
4911
                                    if (nextY > tempY)
4912
                                    {
4913
                                        newY = tempY + gridSetting.Length;
4914
                                        if (newY > nextY)
4915
                                            newY = (point[1] + nextY) / 2;
4916
                                    }
4917
                                    else
4918
                                    {
4919
                                        newY = tempY - gridSetting.Length;
4920
                                        if (newY < nextY)
4921
                                            newY = (point[1] + nextY) / 2;
4922
                                    }
4923
                                    resultPoint = new double[] { resultPoint[0], newY };
4924
                                }
4925
                            }
4926
                        }
4927
                        else if (i == targetVertices.Count - 1 && targetVertices.Count != 2)
4928
                        {
4929
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4930
                            bool containZeroLength = false;
4931
                            if (connSymbol != null)
4932
                            {
4933
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4934
                                {
4935
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4936
                                        containZeroLength = true;
4937
                                }
4938
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4939
                                {
4940
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4941
                                        containZeroLength = true;
4942
                                }
4943
                            }
4944

    
4945
                            if (connSymbol == null ||
4946
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4947
                                containZeroLength)
4948
                            {
4949
                                bool bCalcX = false;
4950
                                bool bCalcY = false;
4951
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4952
                                    bCalcX = true;
4953
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4954
                                    bCalcY = true;
4955
                                else
4956
                                {
4957
                                    bCalcX = true;
4958
                                    bCalcY = true;
4959
                                }
4960

    
4961
                                if (bCalcX)
4962
                                {
4963
                                    double nextX = targetVertices[i - 1][0];
4964
                                    double newX = 0;
4965
                                    if (nextX > tempX)
4966
                                    {
4967
                                        newX = tempX + gridSetting.Length;
4968
                                        if (newX > nextX)
4969
                                            newX = (point[0] + nextX) / 2;
4970
                                    }
4971
                                    else
4972
                                    {
4973
                                        newX = tempX - gridSetting.Length;
4974
                                        if (newX < nextX)
4975
                                            newX = (point[0] + nextX) / 2;
4976
                                    }
4977
                                    resultPoint = new double[] { newX, resultPoint[1] };
4978
                                }
4979

    
4980
                                if (bCalcY)
4981
                                {
4982
                                    double nextY = targetVertices[i - 1][1];
4983
                                    double newY = 0;
4984
                                    if (nextY > tempY)
4985
                                    {
4986
                                        newY = tempY + gridSetting.Length;
4987
                                        if (newY > nextY)
4988
                                            newY = (point[1] + nextY) / 2;
4989
                                    }
4990
                                    else
4991
                                    {
4992
                                        newY = tempY - gridSetting.Length;
4993
                                        if (newY < nextY)
4994
                                            newY = (point[1] + nextY) / 2;
4995
                                    }
4996
                                    resultPoint = new double[] { resultPoint[0], newY };
4997
                                }
4998
                            }
4999
                        }
5000
                        break;
5001
                    }
5002
                }
5003
            }
5004

    
5005
            x = resultPoint[0];
5006
            y = resultPoint[1];
5007

    
5008
            return targetConnector;
5009
        }
5010

    
5011
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
5012
        {
5013
            LMConnector result = null;
5014
            List<LMConnector> connectors = new List<LMConnector>();
5015
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5016

    
5017
            if (modelItem != null)
5018
            {
5019
                foreach (LMRepresentation rep in modelItem.Representations)
5020
                {
5021
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5022
                        connectors.Add(dataSource.GetConnector(rep.Id));
5023
                }
5024

    
5025
                ReleaseCOMObjects(modelItem);
5026
            }
5027

    
5028
            if (connectors.Count == 1)
5029
                result = connectors[0];
5030
            else
5031
                foreach (var item in connectors)
5032
                    ReleaseCOMObjects(item);
5033

    
5034
            return result;
5035
        }
5036

    
5037
        private LMConnector GetLMConnectorFirst(string modelItemID)
5038
        {
5039
            LMConnector result = null;
5040
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5041

    
5042
            if (modelItem != null)
5043
            {
5044
                foreach (LMRepresentation rep in modelItem.Representations)
5045
                {
5046
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" &&
5047
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
5048
                    {
5049
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5050
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
5051
                        {
5052
                            result = connector;
5053
                            break;
5054
                        }
5055
                        else
5056
                        {
5057
                            ReleaseCOMObjects(connector);
5058
                            connector = null;
5059
                        }
5060
                    }
5061
                }
5062
                ReleaseCOMObjects(modelItem);
5063
                modelItem = null;
5064
            }
5065

    
5066
            return result;
5067
        }
5068

    
5069
        private int GetConnectorCount(string modelItemID)
5070
        {
5071
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5072
            int result = 0;
5073
            if (modelItem != null)
5074
            {
5075
                foreach (LMRepresentation rep in modelItem.Representations)
5076
                {
5077
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5078
                        result++;
5079
                    ReleaseCOMObjects(rep);
5080
                }
5081
                ReleaseCOMObjects(modelItem);
5082
            }
5083

    
5084
            return result;
5085
        }
5086

    
5087
        public List<string> GetRepresentations(string modelItemID)
5088
        {
5089
            List<string> result = new List<string>(); ;
5090
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5091
            if (modelItem != null)
5092
            {
5093
                foreach (LMRepresentation rep in modelItem.Representations)
5094
                {
5095
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5096
                        result.Add(rep.Id);
5097
                }
5098
                ReleaseCOMObjects(modelItem);
5099
            }
5100

    
5101
            return result;
5102
        }
5103

    
5104
        private void LineNumberModeling(LineNumber lineNumber)
5105
        {
5106
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5107
            if (line != null)
5108
            {
5109
                double x = 0;
5110
                double y = 0;
5111
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
5112

    
5113
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5114
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
5115
                if (connectedLMConnector != null)
5116
                {
5117
                    Array points = new double[] { 0, x, y };
5118
                    lineNumber.SPPID.SPPID_X = x;
5119
                    lineNumber.SPPID.SPPID_Y = y;
5120
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
5121

    
5122
                    if (_LmLabelPresist != null)
5123
                    {
5124
                        _LmLabelPresist.Commit();
5125
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
5126
                        ReleaseCOMObjects(_LmLabelPresist);
5127
                    }
5128
                }
5129

    
5130
                foreach (var item in connectorVertices)
5131
                    ReleaseCOMObjects(item.Key);
5132
            }
5133
        }
5134
        private void LineNumberCorrectModeling(LineNumber lineNumber)
5135
        {
5136
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5137
            if (line == null || line.SPPID.Vertices == null)
5138
                return;
5139

    
5140
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
5141
            {
5142
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
5143
                if (removeLabel != null)
5144
                {
5145
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
5146
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
5147

    
5148
                    GridSetting gridSetting = GridSetting.GetInstance();
5149
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
5150

    
5151
                    double[] labelRange = null;
5152
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
5153
                    List<double[]> vertices = GetConnectorVertices(connector);
5154

    
5155
                    double[] resultStart = null;
5156
                    double[] resultEnd = null;
5157
                    double distance = double.MaxValue;
5158
                    for (int i = 0; i < vertices.Count - 1; i++)
5159
                    {
5160
                        double[] startPoint = vertices[i];
5161
                        double[] endPoint = vertices[i + 1];
5162
                        foreach (var item in line.SPPID.Vertices)
5163
                        {
5164
                            double[] lineStartPoint = item[0];
5165
                            double[] lineEndPoint = item[item.Count - 1];
5166

    
5167
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
5168
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
5169
                            if (tempDistance < distance)
5170
                            {
5171
                                distance = tempDistance;
5172
                                resultStart = startPoint;
5173
                                resultEnd = endPoint;
5174
                            }
5175
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
5176
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
5177
                            if (tempDistance < distance)
5178
                            {
5179
                                distance = tempDistance;
5180
                                resultStart = startPoint;
5181
                                resultEnd = endPoint;
5182
                            }
5183
                        }
5184
                    }
5185

    
5186
                    if (resultStart != null && resultEnd != null)
5187
                    {
5188
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
5189
                        double lineStartX = 0;
5190
                        double lineStartY = 0;
5191
                        double lineEndX = 0;
5192
                        double lineEndY = 0;
5193
                        double lineNumberX = 0;
5194
                        double lineNumberY = 0;
5195
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
5196
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
5197

    
5198
                        double lineX = (lineStartX + lineEndX) / 2;
5199
                        double lineY = (lineStartY + lineEndY) / 2;
5200
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
5201
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
5202

    
5203
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
5204
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
5205
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
5206
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
5207

    
5208
                        double offsetX = 0;
5209
                        double offsetY = 0;
5210
                        if (slope == SlopeType.HORIZONTAL)
5211
                        {
5212
                            // Line Number 아래
5213
                            if (lineY < lineNumberY)
5214
                            {
5215
                                offsetX = labelCenterX - SPPIDCenterX;
5216
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
5217
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5218
                            }
5219
                            // Line Number 위
5220
                            else
5221
                            {
5222
                                offsetX = labelCenterX - SPPIDCenterX;
5223
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
5224
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5225
                            }
5226
                        }
5227
                        else if (slope == SlopeType.VERTICAL)
5228
                        {
5229
                            // Line Number 오르쪽
5230
                            if (lineX < lineNumberX)
5231
                            {
5232
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
5233
                                offsetY = labelCenterY - SPPIDCenterY;
5234
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5235
                            }
5236
                            // Line Number 왼쪽
5237
                            else
5238
                            {
5239
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
5240
                                offsetY = labelCenterY - SPPIDCenterY;
5241
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5242
                            }
5243
                        }
5244

    
5245
                        if (offsetY != 0 || offsetY != 0)
5246
                        {
5247
                            if (connector.ConnectItem1SymbolObject != null &&
5248
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
5249
                            {
5250
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
5251

    
5252
                                double x1, y1, x2, y2, originX, originY;
5253
                                symbol.Range(out x1, out y1, out x2, out y2);
5254
                                symbol.GetOrigin(out originX, out originY);
5255
                                if (originX < lineNumber.SPPID.SPPID_X)
5256
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5257
                                else
5258
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5259
                            }
5260
                            else if (connector.ConnectItem2SymbolObject != null &&
5261
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
5262
                            {
5263
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
5264

    
5265
                                double x1, y1, x2, y2, originX, originY;
5266
                                symbol.Range(out x1, out y1, out x2, out y2);
5267
                                symbol.GetOrigin(out originX, out originY);
5268
                                if (originX < lineNumber.SPPID.SPPID_X)
5269
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5270
                                else
5271
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5272
                            }
5273

    
5274
                            radApp.ActiveSelectSet.RemoveAll();
5275
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
5276
                            if (dependency != null)
5277
                            {
5278
                                radApp.ActiveSelectSet.Add(dependency);
5279
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
5280
                                transform.DefineByMove2d(-offsetX, -offsetY);
5281
                                radApp.ActiveSelectSet.Transform(transform, true);
5282
                                radApp.ActiveSelectSet.RemoveAll();
5283
                            }
5284
                        }
5285

    
5286
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
5287
                        {
5288
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
5289
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
5290
                        }
5291
                    }
5292

    
5293

    
5294
                    ReleaseCOMObjects(connector);
5295
                    connector = null;
5296
                }
5297

    
5298
                ReleaseCOMObjects(removeLabel);
5299
                removeLabel = null;
5300
            }
5301
        }
5302
        /// <summary>
5303
        /// Flow Mark Modeling
5304
        /// </summary>
5305
        /// <param name="line"></param>
5306
        private void FlowMarkModeling(Line line)
5307
        {
5308
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
5309
            {
5310
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
5311
                if (connector != null)
5312
                {
5313
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
5314
                    List<double[]> vertices = GetConnectorVertices(connector);
5315
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
5316
                    double[] point = vertices[vertices.Count - 1];
5317
                    Array array = new double[] { 0, point[0], point[1] };
5318
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, null, null, LabeledItem: connector.AsLMRepresentation());
5319
                    if (_LMLabelPersist != null)
5320
                    {
5321
                        _LMLabelPersist.Commit();
5322
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
5323
                        ReleaseCOMObjects(_LMLabelPersist);
5324
                    }
5325
                }
5326
            }
5327
        }
5328

    
5329
        /// <summary>
5330
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
5331
        /// </summary>
5332
        /// <param name="lineNumber"></param>
5333
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
5334
        {
5335
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
5336
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
5337
            {
5338
                if (a.ATTRIBUTE == "Tag Seq No")
5339
                    return 1;
5340
                else if (b.ATTRIBUTE == "Tag Seq No")
5341
                    return -1;
5342

    
5343
                return 0;
5344
            }
5345

    
5346
            foreach (LineRun run in lineNumber.RUNS)
5347
            {
5348
                foreach (var item in run.RUNITEMS)
5349
                {
5350
                    if (item.GetType() == typeof(Line))
5351
                    {
5352
                        Line line = item as Line;
5353
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
5354
                        {
5355
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5356
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5357
                            {
5358
                                foreach (var attribute in lineNumber.ATTRIBUTES)
5359
                                {
5360
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
5361
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5362
                                    {
5363
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5364
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
5365
                                        {
5366
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5367
                                            if (_FluidSystemAttribute != null)
5368
                                            {
5369
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
5370
                                                if (dt.Rows.Count == 1)
5371
                                                {
5372
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5373
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5374
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5375
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5376
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5377

    
5378
                                                    if (_LMAAttribute != null)
5379
                                                    {
5380
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5381
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5382
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
5383
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5384
                                                    }
5385
                                                }
5386
                                                if (dt != null)
5387
                                                    dt.Dispose();
5388
                                            }
5389
                                        }
5390
                                        else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(attribute.VALUE) && _LMAAttribute != null)
5391
                                        {
5392
                                            DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", attribute.VALUE));
5393

    
5394
                                            if (rows.Length.Equals(1))
5395
                                            {
5396
                                                if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5397
                                                    attribute.VALUE = rows[0]["MetricStr"].ToString();
5398
                                                else
5399
                                                    attribute.VALUE = rows[0]["InchStr"].ToString();
5400

    
5401
                                                if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5402
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5403
                                                else if (_LMAAttribute.get_Value() != attribute.VALUE)
5404
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5405
                                            }
5406
                                        }
5407
                                        else if (_LMAAttribute != null)
5408
                                        {
5409
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5410
                                                _LMAAttribute.set_Value(attribute.VALUE);
5411
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
5412
                                                _LMAAttribute.set_Value(attribute.VALUE);
5413
                                        }
5414
                                    }
5415
                                }
5416
                                _LMModelItem.Commit();
5417
                            }
5418
                            if (_LMModelItem != null)
5419
                                ReleaseCOMObjects(_LMModelItem);
5420
                            endLine.Add(line.SPPID.ModelItemId);
5421
                        }
5422
                    }
5423
                }
5424
            }
5425
        }
5426

    
5427
        /// <summary>
5428
        /// Symbol Attribute 입력 메서드
5429
        /// </summary>
5430
        /// <param name="item"></param>
5431
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
5432
        {
5433
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
5434
            string sRep = null;
5435
            string sModelID = null;
5436
            if (targetItem.GetType() == typeof(Symbol))
5437
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
5438
            else if (targetItem.GetType() == typeof(Equipment))
5439
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
5440
            else if (targetItem.GetType() == typeof(Line))
5441
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
5442

    
5443
            if (!string.IsNullOrEmpty(sRep))
5444
            {
5445
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
5446
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
5447
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5448

    
5449
                foreach (var item in targetAttributes)
5450
                {
5451
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5452
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5453
                    {
5454
                        if (!mapping.IsText)
5455
                        {
5456
                            LMAAttribute _LMAAttribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5457
                            if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5458
                            {
5459
                                DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5460

    
5461
                                if (rows.Length.Equals(1))
5462
                                {
5463
                                    if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5464
                                        item.VALUE = rows[0]["MetricStr"].ToString();
5465
                                    else
5466
                                        item.VALUE = rows[0]["InchStr"].ToString();
5467

    
5468
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5469
                                        _LMAAttribute.set_Value(item.VALUE);
5470
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5471
                                        _LMAAttribute.set_Value(item.VALUE);
5472
                                }
5473
                            }
5474
                            else if (_LMAAttribute != null)
5475
                            {
5476
                                _LMAAttribute.set_Value(item.VALUE);
5477
                                // OPC 일경우 Attribute 저장
5478
                                if (targetItem.GetType() == typeof(Symbol))
5479
                                {
5480
                                    Symbol symbol = targetItem as Symbol;
5481
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
5482
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
5483
                                }
5484
                            }
5485
                        }
5486
                        else
5487
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
5488
                    }
5489
                }
5490
                _LMModelItem.Commit();
5491

    
5492
                ReleaseCOMObjects(_Attributes);
5493
                ReleaseCOMObjects(_LMModelItem);
5494
                ReleaseCOMObjects(_LMSymbol);
5495
            }
5496
            else if (!string.IsNullOrEmpty(sModelID))
5497
            {
5498
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
5499
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5500

    
5501
                foreach (var item in targetAttributes)
5502
                {
5503
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5504
                    if (mapping == null)
5505
                        continue;
5506

    
5507
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5508
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
5509
                    {
5510
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5511
                        if (_FluidSystemAttribute != null)
5512
                        {
5513
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
5514
                            if (dt.Rows.Count == 1)
5515
                            {
5516
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5517
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5518
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5519
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5520
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5521

    
5522
                                if (_LMAAttribute != null)
5523
                                {
5524
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5525
                                        _LMAAttribute.set_Value(item.VALUE);
5526
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5527
                                        _LMAAttribute.set_Value(item.VALUE);
5528
                                }
5529
                            }
5530
                            if (dt != null)
5531
                                dt.Dispose();
5532
                        }
5533
                    }
5534
                    else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5535
                    {
5536
                        DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5537

    
5538
                        if (rows.Length.Equals(1))
5539
                        {
5540
                            if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5541
                                item.VALUE = rows[0]["MetricStr"].ToString();
5542
                            else
5543
                                item.VALUE = rows[0]["InchStr"].ToString();
5544

    
5545
                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5546
                                _LMAAttribute.set_Value(item.VALUE);
5547
                            else if (_LMAAttribute.get_Value() != item.VALUE)
5548
                                _LMAAttribute.set_Value(item.VALUE);
5549
                        }
5550
                    }
5551
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5552
                    {
5553
                        if (!mapping.IsText)
5554
                        {
5555
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5556
                            if (_Attribute != null)
5557
                                _Attribute.set_Value(item.VALUE);
5558
                        }
5559
                    }
5560
                }
5561
                _LMModelItem.Commit();
5562

    
5563
                ReleaseCOMObjects(_Attributes);
5564
                ReleaseCOMObjects(_LMModelItem);
5565
            }
5566
        }
5567

    
5568
        /// <summary>
5569
        /// Input SpecBreak Attribute
5570
        /// </summary>
5571
        /// <param name="specBreak"></param>
5572
        private void InputSpecBreakAttribute(SpecBreak specBreak)
5573
        {
5574
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
5575
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
5576

    
5577
            if (upStreamObj != null &&
5578
                downStreamObj != null)
5579
            {
5580
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
5581

    
5582
                if (targetLMConnector != null)
5583
                {
5584
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
5585
                    {
5586
                        string symbolPath = _LMLabelPersist.get_FileName();
5587
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
5588
                        if (mapping != null)
5589
                        {
5590
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
5591
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5592
                            {
5593
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
5594
                                if (values.Length == 2)
5595
                                {
5596
                                    string upStreamValue = values[0];
5597
                                    string downStreamValue = values[1];
5598

    
5599
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
5600
                                }
5601
                            }
5602
                        }
5603
                    }
5604

    
5605
                    ReleaseCOMObjects(targetLMConnector);
5606
                }
5607
            }
5608

    
5609

    
5610
            #region 내부에서만 쓰는 메서드
5611
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
5612
            {
5613
                Symbol upStreamSymbol = _upStreamObj as Symbol;
5614
                Line upStreamLine = _upStreamObj as Line;
5615
                Symbol downStreamSymbol = _downStreamObj as Symbol;
5616
                Line downStreamLine = _downStreamObj as Line;
5617
                // 둘다 Line일 경우
5618
                if (upStreamLine != null && downStreamLine != null)
5619
                {
5620
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5621
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5622
                }
5623
                // 둘다 Symbol일 경우
5624
                else if (upStreamSymbol != null && downStreamSymbol != null)
5625
                {
5626
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
5627
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5628
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5629

    
5630
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5631
                    {
5632
                        if (connector.get_ItemStatus() != "Active")
5633
                            continue;
5634

    
5635
                        if (connector.Id != zeroLenthConnector.Id)
5636
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5637
                    }
5638

    
5639
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5640
                    {
5641
                        if (connector.get_ItemStatus() != "Active")
5642
                            continue;
5643

    
5644
                        if (connector.Id != zeroLenthConnector.Id)
5645
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5646
                    }
5647

    
5648
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5649
                    {
5650
                        if (connector.get_ItemStatus() != "Active")
5651
                            continue;
5652

    
5653
                        if (connector.Id != zeroLenthConnector.Id)
5654
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5655
                    }
5656

    
5657
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5658
                    {
5659
                        if (connector.get_ItemStatus() != "Active")
5660
                            continue;
5661

    
5662
                        if (connector.Id != zeroLenthConnector.Id)
5663
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5664
                    }
5665

    
5666
                    ReleaseCOMObjects(zeroLenthConnector);
5667
                    ReleaseCOMObjects(upStreamLMSymbol);
5668
                    ReleaseCOMObjects(downStreamLMSymbol);
5669
                }
5670
                else if (upStreamSymbol != null && downStreamLine != null)
5671
                {
5672
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
5673
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5674
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5675

    
5676
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5677
                    {
5678
                        if (connector.get_ItemStatus() != "Active")
5679
                            continue;
5680

    
5681
                        if (connector.Id == zeroLenthConnector.Id)
5682
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5683
                    }
5684

    
5685
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5686
                    {
5687
                        if (connector.get_ItemStatus() != "Active")
5688
                            continue;
5689

    
5690
                        if (connector.Id == zeroLenthConnector.Id)
5691
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5692
                    }
5693

    
5694
                    ReleaseCOMObjects(zeroLenthConnector);
5695
                    ReleaseCOMObjects(upStreamLMSymbol);
5696
                }
5697
                else if (upStreamLine != null && downStreamSymbol != null)
5698
                {
5699
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
5700
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5701
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5702

    
5703
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5704
                    {
5705
                        if (connector.get_ItemStatus() != "Active")
5706
                            continue;
5707

    
5708
                        if (connector.Id == zeroLenthConnector.Id)
5709
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5710
                    }
5711

    
5712
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5713
                    {
5714
                        if (connector.get_ItemStatus() != "Active")
5715
                            continue;
5716

    
5717
                        if (connector.Id == zeroLenthConnector.Id)
5718
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5719
                    }
5720

    
5721
                    ReleaseCOMObjects(zeroLenthConnector);
5722
                    ReleaseCOMObjects(downStreamLMSymbol);
5723
                }
5724
            }
5725

    
5726
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
5727
            {
5728
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5729
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5730
                {
5731
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5732
                    if (_LMAAttribute != null)
5733
                    {
5734
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5735
                            _LMAAttribute.set_Value(value);
5736
                        else if (_LMAAttribute.get_Value() != value)
5737
                            _LMAAttribute.set_Value(value);
5738
                    }
5739

    
5740
                    _LMModelItem.Commit();
5741
                }
5742
                if (_LMModelItem != null)
5743
                    ReleaseCOMObjects(_LMModelItem);
5744
            }
5745

    
5746
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
5747
            {
5748
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
5749
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5750
                {
5751
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5752
                    if (_LMAAttribute != null)
5753
                    {
5754
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5755
                            _LMAAttribute.set_Value(value);
5756
                        else if (_LMAAttribute.get_Value() != value)
5757
                            _LMAAttribute.set_Value(value);
5758
                    }
5759

    
5760
                    _LMModelItem.Commit();
5761
                }
5762
                if (_LMModelItem != null)
5763
                    ReleaseCOMObjects(_LMModelItem);
5764
            }
5765
            #endregion
5766
        }
5767

    
5768
        private void InputEndBreakAttribute(EndBreak endBreak)
5769
        {
5770
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5771
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5772

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

    
5825
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5826
                            if (modelItemIDs.Count == 1)
5827
                            {
5828
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5829
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5830
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5831
                                {
5832
                                    bool result = false;
5833
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5834
                                    {
5835
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5836
                                            result = true;
5837
                                        ReleaseCOMObjects(loop);
5838
                                    }
5839

    
5840
                                    if (result)
5841
                                    {
5842
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5843
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5844
                                        //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5845
                                        //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5846
                                        ZeroLengthModelItem.Commit();
5847
                                    }
5848
                                    else
5849
                                    {
5850
                                        List<string> loopModelItems = new List<string>();
5851
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5852
                                        {
5853
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5854
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5855
                                            {
5856
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5857
                                                    loopModelItems.Add(loop.ModelItemID);
5858
                                                ReleaseCOMObjects(loop);
5859
                                            }
5860
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5861
                                            {
5862
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5863
                                                    loopModelItems.Add(loop.ModelItemID);
5864
                                                ReleaseCOMObjects(loop);
5865
                                            }
5866
                                            ReleaseCOMObjects(_symbol);
5867
                                            _symbol = null;
5868
                                        }
5869
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5870
                                        {
5871
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5872
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5873
                                            {
5874
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5875
                                                    loopModelItems.Add(loop.ModelItemID);
5876
                                                ReleaseCOMObjects(loop);
5877
                                            }
5878
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5879
                                            {
5880
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5881
                                                    loopModelItems.Add(loop.ModelItemID);
5882
                                                ReleaseCOMObjects(loop);
5883
                                            }
5884
                                            ReleaseCOMObjects(_symbol);
5885
                                            _symbol = null;
5886
                                        }
5887

    
5888
                                        loopModelItems = loopModelItems.Distinct().ToList();
5889
                                        if (loopModelItems.Count == 1)
5890
                                        {
5891
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5892
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5893
                                            //object value2 = loopModelItem.Attributes["SubUnitNumber"].get_Value();
5894
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5895
                                            //modelItem.Attributes["SubUnitNumber"].set_Value(value2);
5896
                                            modelItem.Commit();
5897
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5898
                                            //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5899
                                            ZeroLengthModelItem.Commit();
5900

    
5901
                                            ReleaseCOMObjects(loopModelItem);
5902
                                            loopModelItem = null;
5903
                                        }
5904
                                    }
5905
                                }
5906
                                else
5907
                                {
5908
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5909
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5910
                                    //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5911
                                    //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5912
                                    ZeroLengthModelItem.Commit();
5913
                                }
5914
                                ReleaseCOMObjects(modelItem);
5915
                                modelItem = null;
5916
                                ReleaseCOMObjects(onlyOne);
5917
                                onlyOne = null;
5918
                            }
5919
                        }
5920
                        ReleaseCOMObjects(connector);
5921
                        connector = null;
5922
                        ReleaseCOMObjects(ZeroLengthModelItem);
5923
                        ZeroLengthModelItem = null;
5924
                    }
5925
                    ReleaseCOMObjects(representation);
5926
                    representation = null;
5927
                }
5928
                ReleaseCOMObjects(labelPersist);
5929
                labelPersist = null;
5930
            }
5931
        }
5932

    
5933
        /// <summary>
5934
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5935
        /// </summary>
5936
        /// <param name="text"></param>
5937
        private void NormalTextModeling(Text text)
5938
        {
5939
            LMSymbol _LMSymbol = null;
5940

    
5941
            LMItemNote _LMItemNote = null;
5942
            LMAAttribute _LMAAttribute = null;
5943

    
5944
            double x = 0;
5945
            double y = 0;
5946
            double angle = text.ANGLE;
5947
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5948

    
5949
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5950
            text.SPPID.SPPID_X = x;
5951
            text.SPPID.SPPID_Y = y;
5952

    
5953
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5954
            if (_LMSymbol != null)
5955
            {
5956
                _LMSymbol.Commit();
5957
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5958
                if (_LMItemNote != null)
5959
                {
5960
                    _LMItemNote.Commit();
5961
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5962
                    if (_LMAAttribute != null)
5963
                    {
5964
                        _LMAAttribute.set_Value(text.VALUE);
5965
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5966
                        _LMItemNote.Commit();
5967

    
5968

    
5969
                        double[] range = null;
5970
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5971
                        {
5972
                            double[] temp = null;
5973
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5974
                            if (temp != null)
5975
                            {
5976
                                if (range == null)
5977
                                    range = temp;
5978
                                else
5979
                                {
5980
                                    range = new double[] {
5981
                                            Math.Min(range[0], temp[0]),
5982
                                            Math.Min(range[1], temp[1]),
5983
                                            Math.Max(range[2], temp[2]),
5984
                                            Math.Max(range[3], temp[3])
5985
                                        };
5986
                                }
5987
                            }
5988
                        }
5989
                        text.SPPID.Range = range;
5990

    
5991
                        if (_LMAAttribute != null)
5992
                            ReleaseCOMObjects(_LMAAttribute);
5993
                        if (_LMItemNote != null)
5994
                            ReleaseCOMObjects(_LMItemNote);
5995
                    }
5996

    
5997
                    TextCorrectModeling(text);
5998
                }
5999
            }
6000
            if (_LMSymbol != null)
6001
                ReleaseCOMObjects(_LMSymbol);
6002
        }
6003

    
6004
        private void DefaultTextModeling(string value, double x, double y)
6005
        {
6006
            LMSymbol _LMSymbol = null;
6007

    
6008
            LMItemNote _LMItemNote = null;
6009
            LMAAttribute _LMAAttribute = null;
6010

    
6011
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
6012
            if (_LMSymbol != null)
6013
            {
6014
                _LMSymbol.Commit();
6015
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6016
                if (_LMItemNote != null)
6017
                {
6018
                    _LMItemNote.Commit();
6019
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6020
                    if (_LMAAttribute != null)
6021
                    {
6022
                        _LMAAttribute.set_Value(value);
6023
                        _LMItemNote.Commit();
6024

    
6025
                        if (_LMAAttribute != null)
6026
                            ReleaseCOMObjects(_LMAAttribute);
6027
                        if (_LMItemNote != null)
6028
                            ReleaseCOMObjects(_LMItemNote);
6029
                    }
6030
                }
6031
            }
6032
            if (_LMSymbol != null)
6033
                ReleaseCOMObjects(_LMSymbol);
6034
        }
6035

    
6036
        private void AssociationTextModeling(Text text)
6037
        {
6038
            LMSymbol _LMSymbol = null;
6039
            LMConnector connectedLMConnector = null;
6040
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6041
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
6042
            {
6043
                Symbol symbol = owner as Symbol;
6044
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6045
                if (_LMSymbol != null)
6046
                {
6047
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6048
                    {
6049
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6050
                        {
6051
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6052

    
6053
                            if (mapping != null)
6054
                            {
6055
                                double x = 0;
6056
                                double y = 0;
6057

    
6058
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6059
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6060
                                Array array = new double[] { 0, x, y };
6061
                                text.SPPID.SPPID_X = x;
6062
                                text.SPPID.SPPID_Y = y;
6063
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6064
                                if (_LMLabelPersist != null)
6065
                                {
6066
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6067
                                    _LMLabelPersist.Commit();
6068
                                    ReleaseCOMObjects(_LMLabelPersist);
6069
                                }
6070
                            }
6071
                        }
6072
                    }
6073
                }
6074
            }
6075
            else if (owner != null && owner.GetType() == typeof(Line))
6076
            {
6077
                Line line = owner as Line;
6078
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
6079
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
6080

    
6081
                if (connectedLMConnector != null)
6082
                {
6083
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6084
                    {
6085
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6086
                        {
6087
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6088

    
6089
                            if (mapping != null)
6090
                            {
6091
                                double x = 0;
6092
                                double y = 0;
6093
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6094
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6095
                                Array array = new double[] { 0, x, y };
6096

    
6097
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6098
                                if (_LMLabelPersist != null)
6099
                                {
6100
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6101
                                    _LMLabelPersist.Commit();
6102

    
6103
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
6104
                                    if (dependency != null)
6105
                                    {
6106
                                        radApp.ActiveSelectSet.RemoveAll();
6107
                                        radApp.ActiveSelectSet.Add(dependency);
6108
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
6109
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
6110
                                        radApp.ActiveSelectSet.Transform(transform, true);
6111
                                        radApp.ActiveSelectSet.RemoveAll();
6112
                                    }
6113

    
6114
                                    ReleaseCOMObjects(_LMLabelPersist);
6115
                                }
6116
                            }
6117
                        }
6118
                    }
6119
                }
6120
            }
6121
            if (_LMSymbol != null)
6122
                ReleaseCOMObjects(_LMSymbol);
6123
        }
6124

    
6125
        private void TextCorrectModeling(Text text)
6126
        {
6127
            if (text.SPPID.Range == null)
6128
                return;
6129

    
6130
            bool needRemodeling = false;
6131
            bool loop = true;
6132
            GridSetting gridSetting = GridSetting.GetInstance();
6133
            while (loop)
6134
            {
6135
                loop = false;
6136
                foreach (var overlapText in document.TEXTINFOS)
6137
                {
6138
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
6139
                        continue;
6140

    
6141
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
6142
                    {
6143
                        double percentX = 0;
6144
                        double percentY = 0;
6145
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
6146
                        {
6147
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
6148
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
6149
                        }
6150
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
6151
                        {
6152
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
6153
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
6154
                        }
6155

    
6156
                        double tempX = 0;
6157
                        double tempY = 0;
6158
                        bool overlapX = false;
6159
                        bool overlapY = false;
6160
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6161
                        if (percentX >= percentY)
6162
                        {
6163
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6164
                            double move = gridSetting.Length * count;
6165
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
6166
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
6167
                            needRemodeling = true;
6168
                            loop = true;
6169
                        }
6170
                        else
6171
                        {
6172
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6173
                            double move = gridSetting.Length * count;
6174
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
6175
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
6176
                            needRemodeling = true;
6177
                            loop = true;
6178
                        }
6179
                    }
6180
                }
6181
            }
6182

    
6183

    
6184
            if (needRemodeling)
6185
            {
6186
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
6187
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6188
                text.SPPID.RepresentationId = null;
6189

    
6190
                LMItemNote _LMItemNote = null;
6191
                LMAAttribute _LMAAttribute = null;
6192
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
6193
                if (_LMSymbol != null)
6194
                {
6195
                    _LMSymbol.Commit();
6196
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6197
                    if (_LMItemNote != null)
6198
                    {
6199
                        _LMItemNote.Commit();
6200
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6201
                        if (_LMAAttribute != null)
6202
                        {
6203
                            _LMAAttribute.set_Value(text.VALUE);
6204
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6205
                            _LMItemNote.Commit();
6206

    
6207
                            ReleaseCOMObjects(_LMAAttribute);
6208
                            ReleaseCOMObjects(_LMItemNote);
6209
                        }
6210
                    }
6211
                }
6212

    
6213
                ReleaseCOMObjects(symbol);
6214
                symbol = null;
6215
                ReleaseCOMObjects(_LMItemNote);
6216
                _LMItemNote = null;
6217
                ReleaseCOMObjects(_LMAAttribute);
6218
                _LMAAttribute = null;
6219
                ReleaseCOMObjects(_LMSymbol);
6220
                _LMSymbol = null;
6221
            }
6222
        }
6223

    
6224
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
6225
        {
6226
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
6227
            {
6228
                List<Text> allTexts = new List<Text>();
6229
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6230
                LMRepresentation representation = targetLabel.RepresentationObject;
6231
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
6232
                if (targetLabel.RepresentationObject != null && symbol != null)
6233
                {
6234
                    double[] symbolRange = null;
6235
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
6236
                    if (symbolRange != null)
6237
                    {
6238
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
6239
                        {
6240
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
6241
                            if (findText != null)
6242
                            {
6243
                                double[] range = null;
6244
                                GetSPPIDSymbolRange(labelPersist, ref range);
6245
                                findText.SPPID.Range = range;
6246
                                allTexts.Add(findText);
6247
                            }
6248

    
6249
                            ReleaseCOMObjects(labelPersist);
6250
                        }
6251

    
6252
                        if (allTexts.Count > 0)
6253
                        {
6254
                            #region Sort Text By Y
6255
                            allTexts.Sort(SortTextByY);
6256
                            int SortTextByY(Text a, Text b)
6257
                            {
6258
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
6259
                            }
6260
                            #endregion
6261

    
6262
                            #region 정렬하기전 방향
6263
                            List<Text> left = new List<Text>();
6264
                            List<Text> down = new List<Text>();
6265
                            List<Text> right = new List<Text>();
6266
                            List<Text> up = new List<Text>();
6267
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
6268
                            foreach (var loopText in allTexts)
6269
                            {
6270
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
6271
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
6272
                                double originX = 0;
6273
                                double originY = 0;
6274
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6275
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6276

    
6277
                                if (angle < 45)
6278
                                {
6279
                                    // Text 오른쪽
6280
                                    if (textCenterX > originX)
6281
                                        right.Add(loopText);
6282
                                    // Text 왼쪽
6283
                                    else
6284
                                        left.Add(loopText);
6285
                                }
6286
                                else
6287
                                {
6288
                                    // Text 아래쪽
6289
                                    if (textCenterY > originY)
6290
                                        down.Add(loopText);
6291
                                    // Text 위쪽
6292
                                    else
6293
                                        up.Add(loopText);
6294
                                }
6295
                            }
6296

    
6297
                            #endregion
6298

    
6299
                            foreach (var texts in sortTexts)
6300
                            {
6301
                                if (texts.Count == 0)
6302
                                    continue;
6303

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

    
6341
                                double gapX = 0;
6342
                                double gapY = 0;
6343
                                if (angle < 45)
6344
                                {
6345
                                    // Text 오른쪽
6346
                                    if (textCenterX > originX)
6347
                                    {
6348
                                        gapX = rangeMinX[0] - symbolRange[2];
6349
                                        gapY = allTextCenterY - symbolCenterY;
6350
                                    }
6351
                                    // Text 왼쪽
6352
                                    else
6353
                                    {
6354
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
6355
                                        gapY = allTextCenterY - symbolCenterY;
6356
                                    }
6357
                                }
6358
                                else
6359
                                {
6360
                                    // Text 아래쪽
6361
                                    if (textCenterY > originY)
6362
                                    {
6363
                                        gapX = allTextCenterX - symbolCenterX;
6364
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
6365
                                    }
6366
                                    // Text 위쪽
6367
                                    else
6368
                                    {
6369
                                        gapX = allTextCenterX - symbolCenterX;
6370
                                        gapY = rangeMinY[0] - symbolRange[3];
6371
                                    }
6372
                                }
6373

    
6374
                                foreach (var item in texts)
6375
                                {
6376
                                    MoveText(item, gapX, gapY);
6377
                                    RemodelingAssociationText(item);
6378
                                }
6379
                                #endregion
6380
                            }
6381
                        }
6382
                    }
6383
                }
6384

    
6385
                void MoveText(Text moveText, double x, double y)
6386
                {
6387
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
6388
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
6389
                    moveText.SPPID.Range = new double[] {
6390
                        moveText.SPPID.Range[0] - x,
6391
                        moveText.SPPID.Range[1]- y,
6392
                        moveText.SPPID.Range[2]- x,
6393
                        moveText.SPPID.Range[3]- y
6394
                    };
6395
                }
6396

    
6397
                endTexts.AddRange(allTexts);
6398

    
6399
                ReleaseCOMObjects(targetLabel);
6400
                targetLabel = null;
6401
                ReleaseCOMObjects(representation);
6402
                representation = null;
6403
            }
6404
        }
6405

    
6406
        private void RemodelingAssociationText(Text text)
6407
        {
6408
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6409
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
6410
            removeLabel.Commit();
6411
            ReleaseCOMObjects(removeLabel);
6412
            removeLabel = null;
6413

    
6414
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6415
            if (owner != null && owner.GetType() == typeof(Symbol))
6416
            {
6417
                Symbol symbol = owner as Symbol;
6418
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6419
                if (_LMSymbol != null)
6420
                {
6421
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
6422
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6423
                    {
6424
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6425

    
6426
                        if (mapping != null)
6427
                        {
6428
                            double x = 0;
6429
                            double y = 0;
6430

    
6431
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
6432
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6433
                            if (_LMLabelPersist != null)
6434
                            {
6435
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6436
                                _LMLabelPersist.Commit();
6437
                            }
6438
                            ReleaseCOMObjects(_LMLabelPersist);
6439
                            _LMLabelPersist = null;
6440
                        }
6441
                    }
6442
                }
6443
                ReleaseCOMObjects(_LMSymbol);
6444
                _LMSymbol = null;
6445
            }
6446
        }
6447

    
6448
        /// <summary>
6449
        /// Note Modeling
6450
        /// </summary>
6451
        /// <param name="note"></param>
6452
        private void NoteModeling(Note note, List<Note> correctList)
6453
        {
6454
            LMSymbol _LMSymbol = null;
6455
            LMItemNote _LMItemNote = null;
6456
            LMAAttribute _LMAAttribute = null;
6457

    
6458
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
6459
            {
6460
                double x = 0;
6461
                double y = 0;
6462

    
6463
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
6464
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6465
                note.SPPID.SPPID_X = x;
6466
                note.SPPID.SPPID_Y = y;
6467

    
6468
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
6469
                if (_LMSymbol != null)
6470
                {
6471
                    _LMSymbol.Commit();
6472
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6473
                    if (_LMItemNote != null)
6474
                    {
6475
                        _LMItemNote.Commit();
6476
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6477
                        if (_LMAAttribute != null)
6478
                        {
6479
                            _LMAAttribute.set_Value(note.VALUE);
6480
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6481

    
6482
                            double[] range = null;
6483
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6484
                            {
6485
                                double[] temp = null;
6486
                                GetSPPIDSymbolRange(labelPersist, ref temp);
6487
                                if (temp != null)
6488
                                {
6489
                                    if (range == null)
6490
                                        range = temp;
6491
                                    else
6492
                                    {
6493
                                        range = new double[] {
6494
                                            Math.Min(range[0], temp[0]),
6495
                                            Math.Min(range[1], temp[1]),
6496
                                            Math.Max(range[2], temp[2]),
6497
                                            Math.Max(range[3], temp[3])
6498
                                        };
6499
                                    }
6500
                                }
6501
                            }
6502
                            if (range != null)
6503
                                correctList.Add(note);
6504
                            note.SPPID.Range = range;
6505

    
6506

    
6507
                            _LMItemNote.Commit();
6508
                        }
6509
                    }
6510
                }
6511
            }
6512

    
6513
            if (_LMAAttribute != null)
6514
                ReleaseCOMObjects(_LMAAttribute);
6515
            if (_LMItemNote != null)
6516
                ReleaseCOMObjects(_LMItemNote);
6517
            if (_LMSymbol != null)
6518
                ReleaseCOMObjects(_LMSymbol);
6519
        }
6520

    
6521
        private void NoteCorrectModeling(Note note, List<Note> endList)
6522
        {
6523
            bool needRemodeling = false;
6524
            bool loop = true;
6525
            GridSetting gridSetting = GridSetting.GetInstance();
6526
            while (loop)
6527
            {
6528
                loop = false;
6529
                foreach (var overlap in endList)
6530
                {
6531
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
6532
                    {
6533
                        double tempX = 0;
6534
                        double tempY = 0;
6535
                        bool overlapX = false;
6536
                        bool overlapY = false;
6537
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6538
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
6539
                        if (overlapY && angle >= 45)
6540
                        {
6541
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6542
                            double move = gridSetting.Length * count;
6543
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
6544
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
6545
                            needRemodeling = true;
6546
                            loop = true;
6547
                        }
6548
                        if (overlapX && angle <= 45)
6549
                        {
6550
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6551
                            double move = gridSetting.Length * count;
6552
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
6553
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
6554
                            needRemodeling = true;
6555
                            loop = true;
6556
                        }
6557
                    }
6558
                }
6559
            }
6560

    
6561

    
6562
            if (needRemodeling)
6563
            {
6564
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
6565
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6566
                note.SPPID.RepresentationId = null;
6567

    
6568
                LMItemNote _LMItemNote = null;
6569
                LMAAttribute _LMAAttribute = null;
6570
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
6571
                if (_LMSymbol != null)
6572
                {
6573
                    _LMSymbol.Commit();
6574
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6575
                    if (_LMItemNote != null)
6576
                    {
6577
                        _LMItemNote.Commit();
6578
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6579
                        if (_LMAAttribute != null)
6580
                        {
6581
                            _LMAAttribute.set_Value(note.VALUE);
6582
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6583
                            _LMItemNote.Commit();
6584

    
6585
                            ReleaseCOMObjects(_LMAAttribute);
6586
                            ReleaseCOMObjects(_LMItemNote);
6587
                        }
6588
                    }
6589
                }
6590

    
6591
                ReleaseCOMObjects(symbol);
6592
                symbol = null;
6593
                ReleaseCOMObjects(_LMItemNote);
6594
                _LMItemNote = null;
6595
                ReleaseCOMObjects(_LMAAttribute);
6596
                _LMAAttribute = null;
6597
                ReleaseCOMObjects(_LMSymbol);
6598
                _LMSymbol = null;
6599
            }
6600

    
6601
            endList.Add(note);
6602
        }
6603

    
6604
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
6605
        {
6606
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6607
            if (modelItem != null)
6608
            {
6609
                foreach (LMRepresentation rep in modelItem.Representations)
6610
                {
6611
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
6612
                    {
6613
                        LMConnector connector = dataSource.GetConnector(rep.Id);
6614
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
6615
                        {
6616
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
6617
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6618
                            if (modelItemIds.Count == 1)
6619
                            {
6620
                                string joinModelItemId = modelItemIds[0];
6621
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6622
                                if (survivorId != null)
6623
                                    break;
6624
                            }
6625
                        }
6626
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
6627
                        {
6628
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
6629
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6630
                            if (modelItemIds.Count == 1)
6631
                            {
6632
                                string joinModelItemId = modelItemIds[0];
6633
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6634
                                if (survivorId != null)
6635
                                    break;
6636
                            }
6637
                        }
6638
                    }
6639
                }
6640
            }
6641
        }
6642

    
6643
        /// <summary>
6644
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
6645
        /// </summary>
6646
        /// <param name="x"></param>
6647
        /// <param name="y"></param>
6648
        /// <param name="originX"></param>
6649
        /// <param name="originY"></param>
6650
        /// <param name="SPPIDLabelLocation"></param>
6651
        /// <param name="location"></param>
6652
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDEtcLocationInfo SPPIDLabelLocation, Location location)
6653
        {
6654
            if (location == Location.None)
6655
            {
6656
                x = originX;
6657
                y = originY;
6658
            }
6659
            else
6660
            {
6661
                if (location.HasFlag(Location.Center))
6662
                {
6663
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
6664
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
6665
                }
6666

    
6667
                if (location.HasFlag(Location.Left))
6668
                    x = SPPIDLabelLocation.X1;
6669
                else if (location.HasFlag(Location.Right))
6670
                    x = SPPIDLabelLocation.X2;
6671

    
6672
                if (location.HasFlag(Location.Down))
6673
                    y = SPPIDLabelLocation.Y1;
6674
                else if (location.HasFlag(Location.Up))
6675
                    y = SPPIDLabelLocation.Y2;
6676
            }
6677
        }
6678

    
6679
        /// <summary>
6680
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
6681
        /// 1. Angle Valve
6682
        /// 2. 3개로 이루어진 Symbol Group
6683
        /// </summary>
6684
        /// <returns></returns>
6685
        private List<Symbol> GetPrioritySymbol()
6686
        {
6687
            DataTable symbolTable = document.SymbolTable;
6688
            // List에 순서대로 쌓는다.
6689
            List<Symbol> symbols = new List<Symbol>();
6690

    
6691
            // Angle Valve 부터
6692
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
6693
            {
6694
                if (!symbols.Contains(symbol))
6695
                {
6696
                    double originX = 0;
6697
                    double originY = 0;
6698

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

    
6703
                    SlopeType slopeType1 = SlopeType.None;
6704
                    SlopeType slopeType2 = SlopeType.None;
6705
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
6706
                    {
6707
                        double connectorX = 0;
6708
                        double connectorY = 0;
6709
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
6710
                        if (slopeType1 == SlopeType.None)
6711
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6712
                        else
6713
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6714
                    }
6715

    
6716
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
6717
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
6718
                        symbols.Add(symbol);
6719
                }
6720
            }
6721

    
6722
            List<Symbol> tempSymbols = new List<Symbol>();
6723
            // Conn 갯수 기준
6724
            foreach (var item in document.SYMBOLS)
6725
            {
6726
                if (!symbols.Contains(item))
6727
                    tempSymbols.Add(item);
6728
            }
6729
            tempSymbols.Sort(SPPIDUtil.SortSymbolPriority);
6730
            symbols.AddRange(tempSymbols);
6731

    
6732
            return symbols;
6733
        }
6734

    
6735
        private void SetPriorityLine(List<Line> lines)
6736
        {
6737
            lines.Sort(SortLinePriority);
6738

    
6739
            int SortLinePriority(Line a, Line b)
6740
            {
6741
                int childRetval = CompareChild(a, b);
6742
                if (childRetval != 0)
6743
                {
6744
                    return childRetval;
6745
                }
6746
                else
6747
                { 
6748
                    // Branch 없는것부터
6749
                    int branchRetval = CompareBranchLine(a, b);
6750
                    if (branchRetval != 0)
6751
                    {
6752
                        return branchRetval;
6753
                    }
6754
                    else
6755
                    {
6756
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
6757
                        int connItemRetval = CompareConnItem(a, b);
6758
                        if (connItemRetval != 0)
6759
                        {
6760
                            return connItemRetval;
6761
                        }
6762
                        else
6763
                        {
6764
                            // line 길이
6765
                            int lengthRetval = CompareLength(a, b);
6766
                            if (lengthRetval != 0)
6767
                            {
6768
                                return lengthRetval;
6769
                            }
6770
                            else
6771
                            {
6772
                                // Symbol 연결 갯수
6773
                                int connSymbolRetval = CompareConnSymbol(a, b);
6774
                                if (connSymbolRetval != 0)
6775
                                {
6776
                                    return connSymbolRetval;
6777
                                }
6778
                                else
6779
                                {
6780
                                    // ConnectedItem이 없는것
6781
                                    int noneConnRetval = CompareNoneConn(a, b);
6782
                                    if (noneConnRetval != 0)
6783
                                    {
6784
                                        return noneConnRetval;
6785
                                    }
6786
                                    else
6787
                                    {
6788

    
6789
                                    }
6790
                                }
6791
                            }
6792
                        }
6793
                    }
6794
                }
6795

    
6796
                return 0;
6797
            }
6798

    
6799
            int CompareChild(Line a, Line b)
6800
            {
6801
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6802
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
6803

    
6804
                // 내림차순
6805
                return countA.CompareTo(countB);
6806
            }
6807

    
6808
            int CompareConnSymbol(Line a, Line b)
6809
            {
6810
                List<Connector> connectorsA = a.CONNECTORS
6811
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6812
                    .ToList();
6813

    
6814
                List<Connector> connectorsB = b.CONNECTORS
6815
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6816
                    .ToList();
6817

    
6818
                // 내림차순
6819
                return connectorsA.Count.CompareTo(connectorsB.Count);
6820
            }
6821

    
6822
            int CompareLength(Line a, Line b)
6823
            {
6824
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6825
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6826

    
6827
                // 오름차순
6828
                return lengthB.CompareTo(lengthA);
6829
            }
6830

    
6831
            int CompareConnItem(Line a, Line b)
6832
            {
6833
                List<Connector> connectorsA = a.CONNECTORS
6834
                    .Where(conn => conn.ConnectedObject != null &&
6835
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6836
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6837
                    .ToList();
6838

    
6839
                List<Connector> connectorsB = b.CONNECTORS
6840
                    .Where(conn => conn.ConnectedObject != null &&
6841
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6842
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6843
                    .ToList();
6844

    
6845
                // 내림차순
6846
                return connectorsA.Count.CompareTo(connectorsB.Count);
6847
            }
6848

    
6849
            int CompareBranchLine(Line a, Line b)
6850
            {
6851
                List<Connector> connectorsA = a.CONNECTORS
6852
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6853
                    .ToList();
6854
                List<Connector> connectorsB = b.CONNECTORS
6855
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6856
                    .ToList();
6857

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

    
6862
            int CompareNoneConn(Line a, Line b)
6863
            {
6864
                List<Connector> connectorsA = a.CONNECTORS
6865
                    .Where(conn => conn.ConnectedObject == null)
6866
                    .ToList();
6867

    
6868
                List<Connector> connectorsB = b.CONNECTORS
6869
                    .Where(conn => conn.ConnectedObject == null)
6870
                    .ToList();
6871

    
6872
                // 내림차순
6873
                return connectorsA.Count.CompareTo(connectorsB.Count);
6874
            }
6875
        }
6876

    
6877
        private void SortText(List<Text> texts)
6878
        {
6879
            texts.Sort(Sort);
6880

    
6881
            int Sort(Text a, Text b)
6882
            {
6883
                int yRetval = CompareY(a, b);
6884
                if (yRetval != 0)
6885
                {
6886
                    return yRetval;
6887
                }
6888
                else
6889
                {
6890
                    return CompareX(a, b);
6891
                }
6892
            }
6893

    
6894
            int CompareY(Text a, Text b)
6895
            {
6896
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6897
            }
6898

    
6899
            int CompareX(Text a, Text b)
6900
            {
6901
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6902
            }
6903
        }
6904
        private void SortNote(List<Note> notes)
6905
        {
6906
            notes.Sort(Sort);
6907

    
6908
            int Sort(Note a, Note b)
6909
            {
6910
                int yRetval = CompareY(a, b);
6911
                if (yRetval != 0)
6912
                {
6913
                    return yRetval;
6914
                }
6915
                else
6916
                {
6917
                    return CompareX(a, b);
6918
                }
6919
            }
6920

    
6921
            int CompareY(Note a, Note b)
6922
            {
6923
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6924
            }
6925

    
6926
            int CompareX(Note a, Note b)
6927
            {
6928
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6929
            }
6930
        }
6931

    
6932
        private void SortBranchLines()
6933
        {
6934
            BranchLines.Sort(SortBranchLine);
6935

    
6936
            int SortBranchLine(Line a, Line b)
6937
            {
6938
                int childRetval = CompareChild(a, b);
6939
                if (childRetval != 0)
6940
                {
6941
                    return childRetval;
6942
                }
6943
                else
6944
                {
6945
                    int branchRetval = CompareChildBranch(a, b);
6946
                    if (branchRetval != 0)
6947
                    {
6948
                        return branchRetval;
6949
                    }
6950
                    else
6951
                    {
6952
                        // line 길이
6953
                        int lengthRetval = CompareLength(a, b);
6954
                        if (lengthRetval != 0)
6955
                        {
6956
                            return lengthRetval;
6957
                        }
6958
                    }
6959
                }
6960
                return 0;
6961
            }
6962

    
6963
            int CompareLength(Line a, Line b)
6964
            {
6965
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6966
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6967

    
6968
                // 오름차순
6969
                return lengthB.CompareTo(lengthA);
6970
            }
6971

    
6972
            int CompareChildBranch(Line a, Line b)
6973
            {
6974
                int countA = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
6975
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == a));
6976

    
6977
                int countB = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
6978
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == b));
6979

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

    
6984
            int CompareChild(Line a, Line b)
6985
            {
6986
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6987
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
6988

    
6989
                // 내림차순
6990
                return countA.CompareTo(countB);
6991
            }
6992
        }
6993

    
6994
        private string GetSPPIDFileName(LMModelItem modelItem)
6995
        {
6996
            string symbolPath = null;
6997
            foreach (LMRepresentation rep in modelItem.Representations)
6998
            {
6999
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
7000
                {
7001
                    symbolPath = rep.get_FileName();
7002
                    break;
7003
                }
7004
            }
7005
            return symbolPath;
7006
        }
7007

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

    
7024
        /// <summary>
7025
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
7026
        /// </summary>
7027
        /// <param name="graphicOID"></param>
7028
        /// <param name="milliseconds"></param>
7029
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
7030
        {
7031
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
7032
            {
7033
                double minX = 0;
7034
                double minY = 0;
7035
                double maxX = 0;
7036
                double maxY = 0;
7037
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
7038
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
7039

    
7040
                Thread.Sleep(milliseconds);
7041
            }
7042
        }
7043

    
7044
        /// <summary>
7045
        /// ComObject를 Release
7046
        /// </summary>
7047
        /// <param name="objVars"></param>
7048
        public void ReleaseCOMObjects(params object[] objVars)
7049
        {
7050
            if (objVars != null)
7051
            {
7052
                int intNewRefCount = 0;
7053
                foreach (object obj in objVars)
7054
                {
7055
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
7056
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
7057
                }
7058
            }
7059
        }
7060

    
7061
        /// IDisposable 구현
7062
        ~AutoModeling()
7063
        {
7064
            this.Dispose(false);
7065
        }
7066

    
7067
        private bool disposed;
7068
        public void Dispose()
7069
        {
7070
            this.Dispose(true);
7071
            GC.SuppressFinalize(this);
7072
        }
7073

    
7074
        protected virtual void Dispose(bool disposing)
7075
        {
7076
            if (this.disposed) return;
7077
            if (disposing)
7078
            {
7079
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
7080
            }
7081
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
7082
            this.disposed = true;
7083
        }
7084
    }
7085
}
클립보드 이미지 추가 (최대 크기: 500 MB)