프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ ad3424b7

이력 | 보기 | 이력해설 | 다운로드 (330 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

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

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

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

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

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

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

    
1095
            }
1096

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

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

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

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

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

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

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

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

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

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

    
1292
                        drawingAttributeDT.Dispose();
1293
                    }
1294

    
1295
                    ReleaseCOMObjects(drawing);
1296
                }
1297

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

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

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

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

    
1332
                }
1333
            }
1334
        }
1335

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

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

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

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

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

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

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

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

    
1439
            LMSymbol _LMSymbol = null;
1440

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1705
            return info;
1706
        }
1707

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

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

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

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

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

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

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

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

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

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

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

    
1812
            ReleaseCOMObjects(_TargetItem);
1813
        }
1814

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

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

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

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

    
1857
            ReleaseCOMObjects(_TargetItem);
1858
        }
1859

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

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

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

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

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

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

    
1986
            }
1987
        }
1988

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

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

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

    
2006
            range = tempRange;
2007
        }
2008

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

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

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

    
2043
                ReleaseCOMObjects(_ChildSymbol);
2044
            }
2045
        }
2046

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

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

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

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

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

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

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

    
2140
                                        if (result)
2141
                                            break;
2142
                                    }
2143

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2278
            ReleaseCOMObjects(_LMSymbol);
2279
        }
2280

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2578

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

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

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

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

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

    
2693
                            placeRunInputs.AddPoint(x, y);
2694

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

    
2717
                LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
2718
                if (lMConnector != null)
2719
                {
2720
                    lMConnector.Commit();
2721
                    currentLine.SPPID.ModelItemId = lMConnector.ModelItemID;
2722

    
2723
                    bool bRemodelingStart = false;
2724
                    if (lMSymbolStart != null)
2725
                        NeedReModeling(currentLine, lMSymbolStart, ref bRemodelingStart);
2726
                    bool bRemodelingEnd = false;
2727
                    if (lMSymbolEnd != null)
2728
                        NeedReModeling(currentLine, lMSymbolEnd, ref bRemodelingEnd);
2729

    
2730
                    if (bRemodelingStart || bRemodelingEnd)
2731
                        ReModelingLine(currentLine, lMConnector, lMSymbolStart, lMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2732

    
2733
                    FlowMarkModeling(currentLine);
2734

    
2735
                    ReleaseCOMObjects(lMConnector);
2736

    
2737
                    LMModelItem modelItem = dataSource.GetModelItem(currentLine.SPPID.ModelItemId);
2738
                    if (modelItem != null)
2739
                    {
2740
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2741
                        if (attribute != null)
2742
                            attribute.set_Value("End 1 is upstream (Inlet)");
2743
                        modelItem.Commit();
2744
                    }
2745
                    ReleaseCOMObjects(modelItem);
2746
                    modelItem = null;
2747
                }
2748
                else if (!isBranchModeling)
2749
                {
2750
                    Log.Write("Main Line Modeling : " + currentLine.UID);
2751
                }
2752

    
2753
                List<object> removeLines = currentLine.CONNECTORS.FindAll(x =>
2754
                x.ConnectedObject != null &&
2755
                x.ConnectedObject.GetType() == typeof(Line) &&
2756
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2757
                .Select(x => x.ConnectedObject)
2758
                .ToList();
2759

    
2760
                foreach (var item in removeLines)
2761
                    RemoveLineForModeling(item as Line);
2762

    
2763
                ReleaseCOMObjects(lMAItem);
2764
                lMAItem = null;
2765
                ReleaseCOMObjects(placeRunInputs);
2766
                placeRunInputs = null;
2767
                ReleaseCOMObjects(lMSymbolStart);
2768
                lMSymbolStart = null;
2769
                ReleaseCOMObjects(lMSymbolEnd);
2770
                lMSymbolEnd = null;
2771
            }
2772
        }
2773

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

    
2835
            LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
2836
            if (lMConnector != null)
2837
                lMConnector.Commit();
2838

    
2839
            ReleaseCOMObjects(lMAItem);
2840
            lMAItem = null;
2841
            ReleaseCOMObjects(placeRunInputs);
2842
            placeRunInputs = null;
2843
            ReleaseCOMObjects(lMSymbolStart);
2844
            lMSymbolStart = null;
2845
            ReleaseCOMObjects(lMSymbolEnd);
2846
            lMSymbolEnd = null;
2847

    
2848
            return lMConnector;
2849
        }
2850

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

    
2879
                ReleaseCOMObjects(modelItem);
2880
            }
2881
        }
2882

    
2883
        private void RemoveLine(Line line)
2884
        {
2885
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2886
            if (modelItem != null)
2887
            {
2888
                foreach (LMRepresentation rep in modelItem.Representations)
2889
                {
2890
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2891
                        _placement.PIDRemovePlacement(rep);
2892
                }
2893
                ReleaseCOMObjects(modelItem);
2894
            }
2895
            line.SPPID.ModelItemId = null;
2896
        }
2897

    
2898
        private void GetConnectedLineGroup(Line line, List<Line> group)
2899
        {
2900
            if (!group.Contains(line))
2901
                group.Add(line);
2902

    
2903
            foreach (var connector in line.CONNECTORS)
2904
            {
2905
                if (connector.ConnectedObject != null &&
2906
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2907
                    !group.Contains(connector.ConnectedObject) &&
2908
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2909
                {
2910
                    Line connLine = connector.ConnectedObject as Line;
2911
                    if (line.CONNECTORS.IndexOf(connector) == 0
2912
                    && (!SPPIDUtil.IsBranchLine(connLine, line)))
2913
                    {
2914

    
2915
                        group.Insert(group.IndexOf(line), connLine);
2916
                        GetConnectedLineGroup(connLine, group);
2917
                    }
2918
                    else if (line.CONNECTORS.IndexOf(connector) == 1 && !SPPIDUtil.IsBranchLine(connLine, line))
2919
                    {
2920
                        group.Add(connLine);
2921
                        GetConnectedLineGroup(connLine, group);
2922
                    }
2923
                }
2924
            }
2925
        }
2926

    
2927
        private void LineCoordinateCorrection(List<Line> group)
2928
        {
2929
            // 순서대로 전 Item 기준 정렬
2930
            LineCoordinateCorrectionByStart(group);
2931

    
2932
            // 역으로 심볼이 있을 경우 좌표 보정
2933
            LineCoordinateCorrectionForLastLine(group);
2934
        }
2935

    
2936
        private void LineCoordinateCorrectionByStart(List<Line> group)
2937
        {
2938
            for (int i = 0; i < group.Count; i++)
2939
            {
2940
                Line line = group[i];
2941
                if (i == 0)
2942
                {
2943
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2944
                    if (symbolConnector != null)
2945
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2946
                }
2947
                else if (i != 0)
2948
                {
2949
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2950
                }
2951
            }
2952
        }
2953

    
2954
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2955
        {
2956
            Line checkLine = group[group.Count - 1];
2957
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2958
            if (lastSymbolConnector != null)
2959
            {
2960
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2961
                for (int i = group.Count - 2; i >= 0; i--)
2962
                {
2963
                    Line refLine = group[i + 1];
2964
                    Line changeline = group[i];
2965
                    LineCoordinateCorrectionByConnItem(changeline, refLine);
2966
                }
2967
            }
2968
        }
2969

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

    
2989
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2990
        }
2991
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2992
        {
2993
            bool isReverseX = line.SPPID.END_X - line.SPPID.START_X < 0;
2994
            bool isReverseY = line.SPPID.END_Y - line.SPPID.START_Y < 0;
2995
            double minLength = GridSetting.GetInstance().Length * 0.5;
2996
            double minLengthX = minLength * (!isReverseX ? 1 : -1);
2997
            double minLengthY = minLength * (!isReverseY ? 1 : -1);
2998

    
2999
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3000
            int index = line.CONNECTORS.IndexOf(connector);
3001
            if (index == 0)
3002
            {
3003
                line.SPPID.START_X = x;
3004
                line.SPPID.START_Y = y;
3005
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
3006
                {
3007
                    line.SPPID.END_Y = y;
3008
                    // START_X가 END_X 값을 벗어날 경우 END_X 값 보정
3009
                    if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= minLength)
3010
                    {
3011
                        line.SPPID.END_X = line.SPPID.START_X + minLengthX;
3012
                    }
3013
                }
3014
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
3015
                {
3016
                    line.SPPID.END_X = x;
3017
                    // START_Y가 END_Y 값을 벗어날 경우 END_Y 값 보정
3018
                    if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= minLength)
3019
                    {
3020
                        line.SPPID.END_Y = line.SPPID.START_Y + minLengthY;
3021
                    }
3022
                }
3023
            }
3024
            else
3025
            {
3026
                line.SPPID.END_X = x;
3027
                line.SPPID.END_Y = y;
3028
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
3029
                {
3030
                    line.SPPID.START_Y = y;
3031
                    // END_X가 START_X 값을 벗어날 경우 START_X 값 보정
3032
                    if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= minLength)
3033
                    {
3034
                        line.SPPID.START_X = line.SPPID.END_X - minLengthX;
3035
                    }
3036
                }
3037
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
3038
                {
3039
                    line.SPPID.START_X = x;
3040
                    // END_Y가 START_Y 값을 벗어날 경우 START_Y 값 보정
3041
                    if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= minLength)
3042
                    {
3043
                        line.SPPID.START_Y = line.SPPID.END_Y - minLengthY;
3044
                    }
3045
                }
3046
            }
3047
        }
3048

    
3049
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
3050
        {
3051
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3052
            int index = line.CONNECTORS.IndexOf(connector);
3053
            if (index == 0)
3054
            {
3055
                line.SPPID.START_X = x;
3056
                if (line.SlopeType == SlopeType.VERTICAL)
3057
                    line.SPPID.END_X = x;
3058
            }
3059
            else
3060
            {
3061
                line.SPPID.END_X = x;
3062
                if (line.SlopeType == SlopeType.VERTICAL)
3063
                    line.SPPID.START_X = x;
3064
            }
3065
        }
3066

    
3067
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
3068
        {
3069
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
3070
            int index = line.CONNECTORS.IndexOf(connector);
3071
            if (index == 0)
3072
            {
3073
                line.SPPID.START_Y = y;
3074
                if (line.SlopeType == SlopeType.HORIZONTAL)
3075
                    line.SPPID.END_Y = y;
3076
            }
3077
            else
3078
            {
3079
                line.SPPID.END_Y = y;
3080
                if (line.SlopeType == SlopeType.HORIZONTAL)
3081
                    line.SPPID.START_Y = y;
3082
            }
3083
        }
3084

    
3085
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
3086
        {
3087
            if (symbol != null)
3088
            {
3089
                string repID = symbol.AsLMRepresentation().Id;
3090
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
3091
                string lineUID = line.UID;
3092

    
3093
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
3094
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
3095
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
3096

    
3097
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
3098
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
3099
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
3100

    
3101
                if (startSpecBreak != null || startEndBreak != null)
3102
                    result = true;
3103
            }
3104
        }
3105

    
3106
        /// <summary>
3107
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
3108
        /// </summary>
3109
        /// <param name="lines"></param>
3110
        /// <param name="prevLMConnector"></param>
3111
        /// <param name="startSymbol"></param>
3112
        /// <param name="endSymbol"></param>
3113
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
3114
        {
3115
            string symbolPath = string.Empty;
3116
            #region get symbol path
3117
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
3118
            symbolPath = GetSPPIDFileName(modelItem);
3119
            ReleaseCOMObjects(modelItem);
3120
            #endregion
3121
            bool diagonal = false;
3122
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
3123
                diagonal = true;
3124
            _LMAItem lMAItem = _placement.PIDCreateItem(symbolPath);
3125
            LMConnector newConnector = null;
3126
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
3127
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3128
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3129
            int verticesCount = lineStringGeometry.VertexCount;
3130
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3131

    
3132
            List<double[]> vertices = new List<double[]>();
3133
            for (int i = 1; i <= verticesCount; i++)
3134
            {
3135
                double x = 0;
3136
                double y = 0;
3137
                lineStringGeometry.GetVertex(i, ref x, ref y);
3138
                vertices.Add(new double[] { x, y });
3139
            }
3140

    
3141
            for (int i = 0; i < vertices.Count; i++)
3142
            {
3143
                double[] points = vertices[i];
3144
                // 시작 심볼이 있고 첫번째 좌표일 때
3145
                if (startSymbol != null && i == 0)
3146
                {
3147
                    if (bStart)
3148
                    {
3149
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
3150
                        if (slopeType == SlopeType.HORIZONTAL)
3151
                            placeRunInputs.AddPoint(points[0], -0.1);
3152
                        else if (slopeType == SlopeType.VERTICAL)
3153
                            placeRunInputs.AddPoint(-0.1, points[1]);
3154
                        else
3155
                            placeRunInputs.AddPoint(points[0], -0.1);
3156

    
3157
                        placeRunInputs.AddPoint(points[0], points[1]);
3158
                    }
3159
                    else
3160
                    {
3161
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
3162
                    }
3163
                }
3164
                // 마지막 심볼이 있고 마지막 좌표일 때
3165
                else if (endSymbol != null && i == vertices.Count - 1)
3166
                {
3167
                    if (bEnd)
3168
                    {
3169
                        placeRunInputs.AddPoint(points[0], points[1]);
3170

    
3171
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
3172
                        if (slopeType == SlopeType.HORIZONTAL)
3173
                            placeRunInputs.AddPoint(points[0], -0.1);
3174
                        else if (slopeType == SlopeType.VERTICAL)
3175
                            placeRunInputs.AddPoint(-0.1, points[1]);
3176
                        else
3177
                            placeRunInputs.AddPoint(points[0], -0.1);
3178
                    }
3179
                    else
3180
                    {
3181
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3182
                    }
3183
                }
3184
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
3185
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
3186
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
3187
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
3188
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
3189
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
3190
                else
3191
                    placeRunInputs.AddPoint(points[0], points[1]);
3192
            }
3193

    
3194
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3195
            newConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3196

    
3197
            ReleaseCOMObjects(placeRunInputs);
3198
            ReleaseCOMObjects(lMAItem);
3199
            ReleaseCOMObjects(modelItem);
3200

    
3201
            if (newConnector != null)
3202
            {
3203
                newConnector.Commit();
3204
                if (startSymbol != null && bStart)
3205
                {
3206
                    lMAItem = _placement.PIDCreateItem(symbolPath);
3207
                    placeRunInputs = new PlaceRunInputs();
3208
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
3209
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
3210
                    LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3211
                    if (lMConnector != null)
3212
                    {
3213
                        lMConnector.Commit();
3214
                        RemoveConnectorForReModelingLine(newConnector);
3215
                        ZeroLengthModelItemID.Add(lMConnector.ModelItemID);
3216
                        ReleaseCOMObjects(lMConnector);
3217
                    }
3218
                    ReleaseCOMObjects(placeRunInputs);
3219
                    ReleaseCOMObjects(lMAItem);
3220
                }
3221

    
3222
                if (endSymbol != null && bEnd)
3223
                {
3224
                    if (startSymbol != null)
3225
                    {
3226
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
3227
                        newConnector = dicVertices.First().Key;
3228
                    }
3229

    
3230
                    lMAItem = _placement.PIDCreateItem(symbolPath);
3231
                    placeRunInputs = new PlaceRunInputs();
3232
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
3233
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
3234
                    LMConnector lMConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3235
                    if (lMConnector != null)
3236
                    {
3237
                        lMConnector.Commit();
3238
                        RemoveConnectorForReModelingLine(newConnector);
3239
                        ZeroLengthModelItemIDReverse.Add(lMConnector.ModelItemID);
3240
                        ReleaseCOMObjects(lMConnector);
3241
                    }
3242
                    ReleaseCOMObjects(placeRunInputs);
3243
                    ReleaseCOMObjects(lMAItem);
3244
                }
3245

    
3246
                line.SPPID.ModelItemId = newConnector.ModelItemID;
3247
                ReleaseCOMObjects(newConnector);
3248
            }
3249

    
3250
            ReleaseCOMObjects(modelItem);
3251
        }
3252

    
3253
        /// <summary>
3254
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
3255
        /// </summary>
3256
        /// <param name="connector"></param>
3257
        private void RemoveConnectorForReModelingLine(LMConnector connector)
3258
        {
3259
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
3260
            foreach (var item in dicVertices)
3261
            {
3262
                if (item.Value.Count == 2)
3263
                {
3264
                    bool result = false;
3265
                    foreach (var point in item.Value)
3266
                    {
3267
                        if (point[0] < 0 || point[1] < 0)
3268
                        {
3269
                            result = true;
3270
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
3271
                            break;
3272
                        }
3273
                    }
3274

    
3275
                    if (result)
3276
                        break;
3277
                }
3278
            }
3279
            foreach (var item in dicVertices)
3280
                ReleaseCOMObjects(item.Key);
3281
        }
3282

    
3283
        /// <summary>
3284
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
3285
        /// </summary>
3286
        /// <param name="symbol"></param>
3287
        /// <param name="line"></param>
3288
        /// <returns></returns>
3289
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
3290
        {
3291
            LMSymbol _LMSymbol = null;
3292
            foreach (var connector in symbol.CONNECTORS)
3293
            {
3294
                if (connector.CONNECTEDITEM == line.UID)
3295
                {
3296
                    if (connector.Index == 0)
3297
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3298
                    else
3299
                    {
3300
                        ChildSymbol child = null;
3301
                        foreach (var childSymbol in symbol.ChildSymbols)
3302
                        {
3303
                            if (childSymbol.Connectors.Contains(connector))
3304
                                child = childSymbol;
3305
                            else
3306
                                child = GetChildSymbolByConnector(childSymbol, connector);
3307

    
3308
                            if (child != null)
3309
                                break;
3310
                        }
3311

    
3312
                        if (child != null)
3313
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3314
                    }
3315

    
3316
                    break;
3317
                }
3318
            }
3319

    
3320
            return _LMSymbol;
3321
        }
3322

    
3323
        /// <summary>
3324
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3325
        /// </summary>
3326
        /// <param name="item"></param>
3327
        /// <param name="connector"></param>
3328
        /// <returns></returns>
3329
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3330
        {
3331
            foreach (var childSymbol in item.ChildSymbols)
3332
            {
3333
                if (childSymbol.Connectors.Contains(connector))
3334
                    return childSymbol;
3335
                else
3336
                    return GetChildSymbolByConnector(childSymbol, connector);
3337
            }
3338

    
3339
            return null;
3340
        }
3341

    
3342
        /// <summary>
3343
        /// EndBreak 모델링 메서드
3344
        /// </summary>
3345
        /// <param name="endBreak"></param>
3346
        private void EndBreakModeling(EndBreak endBreak)
3347
        {
3348
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3349
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3350

    
3351
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3352
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3353
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3354

    
3355
            if (targetLMConnector != null)
3356
            {
3357
                // LEADER Line 검사
3358
                bool leaderLine = false;
3359
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3360
                if (symbolMapping != null)
3361
                    leaderLine = symbolMapping.LEADERLINE;
3362

    
3363
                SegmentLocation location;
3364
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3365
                Array array = null;
3366
                if (point != null)
3367
                    array = new double[] { 0, point[0], point[1] };
3368
                else
3369
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3370

    
3371
                LMLabelPersist _LmLabelPersist;
3372

    
3373
                Property property = endBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Freeze");
3374
                if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3375
                {
3376
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3377
                }
3378
                else
3379
                {
3380
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3381
                }
3382

    
3383
                if (_LmLabelPersist != null)
3384
                {
3385
                    _LmLabelPersist.Commit();
3386
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3387
                    if (_LmLabelPersist.ModelItemObject != null)
3388
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3389
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3390

    
3391
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3392

    
3393
                    // end break arrange
3394
                    if (property == null || string.IsNullOrEmpty(property.VALUE) || !property.VALUE.Equals("True"))
3395
                    {
3396
                        MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3397
                    }
3398

    
3399
                    ReleaseCOMObjects(_LmLabelPersist);
3400
                }
3401
                ReleaseCOMObjects(targetLMConnector);
3402
            }
3403
            else
3404
            {
3405
                Log.Write("End Break UID : " + endBreak.UID);
3406
                Log.Write("Can't find targetLMConnector");
3407
            }
3408
        }
3409

    
3410
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3411
        {
3412
            double x = 0, y = 0;
3413
            if (location.HasFlag(SegmentLocation.Up))
3414
                y = GridSetting.GetInstance().Length * 3;
3415
            else if (location.HasFlag(SegmentLocation.Down))
3416
                y = -GridSetting.GetInstance().Length * 3;
3417

    
3418
            if (location.HasFlag(SegmentLocation.Right))
3419
                x = GridSetting.GetInstance().Length * 3;
3420
            else if (location.HasFlag(SegmentLocation.Left))
3421
                x = -GridSetting.GetInstance().Length * 3;
3422

    
3423
            if (x != 0 || y != 0)
3424
            {
3425
                radApp.ActiveSelectSet.RemoveAll();
3426
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3427
                if (dependency != null)
3428
                {
3429
                    radApp.ActiveSelectSet.Add(dependency);
3430
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3431
                    transform.DefineByMove2d(x, y);
3432
                    radApp.ActiveSelectSet.Transform(transform, true);
3433
                    radApp.ActiveSelectSet.RemoveAll();
3434
                }
3435
            }
3436
        }
3437

    
3438
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3439
        {
3440
            string symbolPath = string.Empty;
3441
            #region get symbol path
3442
            if (string.IsNullOrEmpty(changeSymbolPath))
3443
            {
3444
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3445
                symbolPath = GetSPPIDFileName(modelItem);
3446
                ReleaseCOMObjects(modelItem);
3447
            }
3448
            else
3449
                symbolPath = changeSymbolPath;
3450

    
3451
            #endregion
3452

    
3453
            LMConnector newConnector = null;
3454
            dynamic OID = connector.get_GraphicOID().ToString();
3455
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3456
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3457
            int verticesCount = lineStringGeometry.VertexCount;
3458
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3459
            _LMAItem lMAItem = _placement.PIDCreateItem(symbolPath);
3460

    
3461
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3462
            {
3463
                double[] vertices = null;
3464
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3465
                double x = 0;
3466
                double y = 0;
3467
                lineStringGeometry.GetVertex(1, ref x, ref y);
3468

    
3469
                string flowDirection = string.Empty;
3470
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3471
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3472
                    flowDirection = flowAttribute.get_Value().ToString();
3473

    
3474
                if (flowDirection == "End 1 is downstream (Outlet)")
3475
                {
3476
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3477
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3478
                    flowDirection = "End 1 is upstream (Inlet)";
3479
                }
3480
                else
3481
                {
3482
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3483
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3484
                }
3485
                string oldModelItemId = connector.ModelItemID;
3486
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3487
                newConnector = _placement.PIDPlaceRun(lMAItem, placeRunInputs);
3488
                newConnector.Commit();
3489
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3490
                if (!string.IsNullOrEmpty(flowDirection))
3491
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3492
                ReleaseCOMObjects(connector);
3493

    
3494
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3495
                {
3496
                    foreach (var repId in line.SPPID.Representations)
3497
                    {
3498
                        LMConnector _connector = dataSource.GetConnector(repId);
3499
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3500
                        {
3501
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3502
                            {
3503
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3504
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3505
                            }
3506
                        }
3507
                        ReleaseCOMObjects(_connector);
3508
                        _connector = null;
3509
                    }
3510
                }
3511
            }
3512

    
3513
            return newConnector;
3514
        }
3515

    
3516
        /// <summary>
3517
        /// SpecBreak Modeling 메서드
3518
        /// </summary>
3519
        /// <param name="specBreak"></param>
3520
        private void SpecBreakModeling(SpecBreak specBreak)
3521
        {
3522
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3523
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3524

    
3525
            if (upStreamObj != null &&
3526
                downStreamObj != null)
3527
            {
3528
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3529
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) &&
3530
                    targetLMConnector != null &&
3531
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3532
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3533

    
3534
                if (targetLMConnector != null)
3535
                {
3536
                    foreach (var attribute in specBreak.ATTRIBUTES)
3537
                    {
3538
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3539
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3540
                        {
3541
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3542
                            SegmentLocation location;
3543
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3544
                            Array array = null;
3545
                            if (point != null)
3546
                                array = new double[] { 0, point[0], point[1] };
3547
                            else
3548
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3549
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3550

    
3551
                            if (_LmLabelPersist != null)
3552
                            {
3553
                                _LmLabelPersist.Commit();
3554
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3555
                                if (_LmLabelPersist.ModelItemObject != null)
3556
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3557
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3558

    
3559
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3560

    
3561
                                // spec break arrange
3562
                                MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3563

    
3564
                                ReleaseCOMObjects(_LmLabelPersist);
3565
                            }
3566
                        }
3567
                    }
3568

    
3569
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3570
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3571
                    {
3572
                        // temp
3573
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3574
                    }
3575
                    ReleaseCOMObjects(targetLMConnector);
3576
                }
3577
                else
3578
                {
3579
                    Log.Write("Spec Break UID : " + specBreak.UID);
3580
                    Log.Write("Can't find targetLMConnector");
3581
                }
3582
            }
3583
        }
3584

    
3585
        private bool IsRhombus(LMLabelPersist labelPersist, out double x, out double y, out double radius)
3586
        {
3587
            bool result = false;
3588
            x = 0; y = 0; radius = 0;
3589

    
3590
            string oid = labelPersist.get_GraphicOID().ToString();
3591
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3592

    
3593
            if (dependency != null)
3594
            {
3595
                bool isLabel = false;
3596
                foreach (var attributes in dependency.AttributeSets)
3597
                {
3598
                    foreach (var attribute in attributes)
3599
                    {
3600
                        string name = attribute.Name;
3601
                        string value = attribute.GetValue().ToString();
3602
                        if (name == "DrawingItemType" && value == "LabelPersist")
3603
                        {
3604
                            isLabel = true;
3605
                            break;
3606
                        }
3607
                    }
3608
                }
3609
                if (isLabel)
3610
                {
3611
                    double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
3612
                    foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
3613
                    {
3614
                        if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLine2d)
3615
                        {
3616
                            Ingr.RAD2D.Line2d line2D = drawingObject as Ingr.RAD2D.Line2d;
3617

    
3618
                            double x1, y1, x2, y2;
3619
                            line2D.GetStartPoint(out x1, out y1);
3620
                            line2D.GetEndPoint(out x2, out y2);
3621
                            double tX1 = Math.Min(x1, x2), tY1 = Math.Min(y1, y2), tX2 = Math.Max(x1, x2), tY2 = Math.Max(y1, y2);
3622
                            if (minX > tX1)
3623
                                minX = tX1;
3624
                            if (minY > tY1)
3625
                                minY = tY1;
3626
                            if (maxX < tX2)
3627
                                maxX = tX2;
3628
                            if (maxY < tY2)
3629
                                maxY = tY2;
3630
                        }
3631
                    }
3632

    
3633
                    double width = Math.Abs(maxX - minX);
3634
                    double height = Math.Abs(maxY - minY);
3635
                    double ratio = width / height * 100;
3636
                    if (ratio > 99d && ratio < 101d)
3637
                    {
3638
                        result = true;
3639
                    }
3640
                    x = (maxX + minX) / 2d;
3641
                    y = (maxY + minY) / 2d;
3642
                    radius = width / 2d;
3643
                }
3644
            }
3645

    
3646
            return result;
3647
        }
3648

    
3649
        private void MoveSegmentBreak(string connectorID, LMLabelPersist labelPersist)
3650
        {
3651
            bool bFind = false;
3652
            double x, y, radius;
3653
            if (IsRhombus(labelPersist, out x, out y, out radius))
3654
            {
3655
                List<double[]> itemPoints = new List<double[]>();
3656
                LMConnector connector = dataSource.GetConnector(connectorID);
3657
                foreach (LMLabelPersist label in connector.LabelPersists)
3658
                {
3659
                    if (!"Active".Equals(label.get_ItemStatus()))
3660
                        continue;
3661

    
3662
                    if (!label.Id.Equals(labelPersist.Id))
3663
                    {
3664
                        double centerX, centerY, temp;
3665
                        if (IsRhombus(label, out centerX, out centerY, out temp))
3666
                        {
3667
                            bFind = true;
3668
                            itemPoints.Add(new double[] { centerX, centerY });
3669
                        }
3670
                    }
3671
                }
3672
                ReleaseCOMObjects(connector);
3673

    
3674

    
3675
                if (bFind)
3676
                {
3677
                    double[] startPoint = itemPoints.First();
3678
                    itemPoints.RemoveAt(0);
3679

    
3680
                    for (int i = 0; i < 8; i++)
3681
                    {
3682
                        double pointX = 0, pointY = 0;
3683
                        switch (i)
3684
                        {
3685
                            case 0:
3686
                                pointX = startPoint[0] + radius;
3687
                                pointY = startPoint[1] + radius;
3688
                                break;
3689
                            case 1:
3690
                                pointX = startPoint[0] + radius + radius;
3691
                                pointY = startPoint[1];
3692
                                break;
3693
                            case 2:
3694
                                pointX = startPoint[0] + radius;
3695
                                pointY = startPoint[1] - radius;
3696
                                break;
3697
                            case 3:
3698
                                pointX = startPoint[0];
3699
                                pointY = startPoint[1] - radius - radius;
3700
                                break;
3701
                            case 4:
3702
                                pointX = startPoint[0] - radius;
3703
                                pointY = startPoint[1] - radius;
3704
                                break;
3705
                            case 5:
3706
                                pointX = startPoint[0] - radius - radius;
3707
                                pointY = startPoint[1];
3708
                                break;
3709
                            case 6:
3710
                                pointX = startPoint[0] - radius;
3711
                                pointY = startPoint[1] + radius;
3712
                                break;
3713
                            case 7:
3714
                                pointX = startPoint[0];
3715
                                pointY = startPoint[1] + radius + radius;
3716
                                break;
3717
                            default:
3718
                                break;
3719
                        }
3720

    
3721
                        if (!ExistSegmentByPoint(pointX, pointY))
3722
                        {
3723
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
3724
                            if (dependency != null)
3725
                            {
3726
                                radApp.ActiveSelectSet.RemoveAll();
3727
                                radApp.ActiveSelectSet.Add(dependency);
3728
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3729
                                transform.DefineByMove2d(pointX - x, pointY - y);
3730
                                radApp.ActiveSelectSet.Transform(transform, true);
3731
                                radApp.ActiveSelectSet.RemoveAll();
3732
                            }
3733
                            break;
3734
                        }
3735
                    }
3736

    
3737
                    bool ExistSegmentByPoint(double pointX, double pointY)
3738
                    {
3739
                        bool result = false;
3740
                        foreach (var item in itemPoints)
3741
                        {
3742
                            double distance = SPPIDUtil.CalcPointToPointdDistance(item[0], item[1], pointX, pointY);
3743
                            if (Math.Truncate(distance * 1000000000d).Equals(0))
3744
                                result = true;
3745
                        }
3746
                        return result;
3747
                    }
3748
                }
3749
            }
3750

    
3751
            if (!bFind)
3752
                MoveSegmentBestLocation(labelPersist.get_GraphicOID().ToString(), new double[] { x - radius, y - radius, x + radius, y + radius }, itemRange);
3753
        }
3754

    
3755
        LMConnectors GetConnectors()
3756
        {
3757
            LMAFilter filter = new LMAFilter();
3758
            LMACriterion criterion1 = new LMACriterion();
3759
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3760
            criterion1.Operator = "=";
3761
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3762
            criterion1.Conjunctive = true;
3763
            filter.get_Criteria().Add(criterion1);
3764
            filter.ItemType = "Connector";
3765

    
3766
            LMACriterion criterion2 = new LMACriterion();
3767
            criterion2.SourceAttributeName = "ITEMSTATUS";
3768
            criterion2.Operator = "=";
3769
            criterion2.set_ValueAttribute("1");
3770
            criterion2.Conjunctive = true;
3771
            filter.get_Criteria().Add(criterion2);
3772

    
3773
            LMACriterion criterion3 = new LMACriterion();
3774
            criterion3.SourceAttributeName = "INSTOCKPILE";
3775
            criterion3.Operator = "=";
3776
            criterion3.set_ValueAttribute("1");
3777
            criterion3.Conjunctive = true;
3778
            filter.get_Criteria().Add(criterion3);
3779

    
3780
            LMConnectors items = new LMConnectors();
3781
            items.Collect(dataSource, Filter: filter);
3782

    
3783
            ReleaseCOMObjects(filter);
3784
            ReleaseCOMObjects(criterion1);
3785
            ReleaseCOMObjects(criterion2);
3786
            ReleaseCOMObjects(criterion3);
3787

    
3788
            return items;
3789
        }
3790
        LMSymbols GetSymbols()
3791
        {
3792
            LMAFilter filter = new LMAFilter();
3793
            LMACriterion criterion1 = new LMACriterion();
3794
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3795
            criterion1.Operator = "=";
3796
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3797
            criterion1.Conjunctive = true;
3798
            filter.get_Criteria().Add(criterion1);
3799
            filter.ItemType = "Symbol";
3800

    
3801
            LMACriterion criterion2 = new LMACriterion();
3802
            criterion2.SourceAttributeName = "ITEMSTATUS";
3803
            criterion2.Operator = "=";
3804
            criterion2.set_ValueAttribute("1");
3805
            criterion2.Conjunctive = true;
3806
            filter.get_Criteria().Add(criterion2);
3807

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

    
3815
            LMSymbols items = new LMSymbols();
3816
            items.Collect(dataSource, Filter: filter);
3817

    
3818
            ReleaseCOMObjects(filter);
3819
            ReleaseCOMObjects(criterion1);
3820
            ReleaseCOMObjects(criterion2);
3821
            ReleaseCOMObjects(criterion3);
3822

    
3823
            return items;
3824
        }
3825

    
3826
        private void SetConnectorAndSymbolRange()
3827
        {
3828
            itemRange = new List<double[]>();
3829

    
3830
            LMConnectors connectors = GetConnectors();
3831
            foreach (LMConnector connector in connectors)
3832
            {
3833
                List<double[]> vertices = GetConnectorVertices(connector);
3834
                for (int i = 0; i < vertices.Count - 1; i++)
3835
                {
3836
                    double[] point1 = vertices[i];
3837
                    double[] point2 = vertices[i + 1];
3838
                    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]);
3839
                    double gap = 0.0001d;
3840
                    itemRange.Add(new double[] { x1 - gap, y1 - gap, x2 + gap, y2 + gap });
3841
                }
3842
                ReleaseCOMObjects(connector);
3843
            }
3844
            ReleaseCOMObjects(connectors);
3845

    
3846
            LMSymbols symbols = GetSymbols();
3847
            foreach (LMSymbol symbol in symbols)
3848
            {
3849
                string oid = symbol.get_GraphicOID().ToString();
3850
                DrawingObjectBase drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid];
3851
                if (drawingObject != null)
3852
                {
3853
                    double x1, y1, x2, y2;
3854
                    drawingObject.Range(out x1, out y1, out x2, out y2);
3855
                    itemRange.Add(new double[] { x1, y1, x2, y2 });
3856
                }
3857

    
3858
                ReleaseCOMObjects(symbol);
3859
            }
3860
            ReleaseCOMObjects(symbols);
3861
        }
3862

    
3863
        private void MoveSegmentBestLocation(string oid, double[] segmentRange, List<double[]> allRanges)
3864
        {
3865
            double minValue = Math.Min(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3866
            double maxValue = Math.Max(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3867

    
3868
            double maxX = 0, maxY = 0;
3869
            maxX = maxValue * 10;
3870
            maxY = minValue * 10;
3871

    
3872
            double move = minValue / 10d;
3873
            double textGap = minValue / 3d;
3874
            segmentRange = new double[] { segmentRange[0] - textGap, segmentRange[1] - textGap, segmentRange[2] + textGap, segmentRange[3] + textGap };
3875

    
3876

    
3877
            List<double[]> containRanges = new List<double[]>();
3878
            double[] findRange = new double[] {
3879
            segmentRange[0] - maxX, segmentRange[1] - maxY,
3880
            segmentRange[2] + maxX, segmentRange[3] + maxY};
3881

    
3882
            foreach (var range in allRanges)
3883
                if (SPPIDUtil.IsOverlap(findRange, range))
3884
                    containRanges.Add(range);
3885

    
3886
            double movePointX = 0, movePointY = 0, distance = double.MaxValue;
3887
            for (double x = 0; x < maxX; x = x + move)
3888
                for (double y = 0; y < maxY; y = y + move)
3889
                    for (int i = 0; i < 4; i++)
3890
                    {
3891
                        double tempX = 0d, tempY = 0d;
3892
                        switch (i)
3893
                        {
3894
                            case 0:
3895
                                tempX = x;
3896
                                tempY = y;
3897
                                break;
3898
                            case 1:
3899
                                tempX = -x;
3900
                                tempY = y;
3901
                                break;
3902
                            case 2:
3903
                                tempX = -x;
3904
                                tempY = -y;
3905
                                break;
3906
                            case 3:
3907
                                tempX = x;
3908
                                tempY = -y;
3909
                                break;
3910
                            default:
3911
                                break;
3912
                        }
3913

    
3914
                        bool result = true;
3915
                        double[] movedRange = new double[] { segmentRange[0] + tempX, segmentRange[1] + tempY, segmentRange[2] + tempX, segmentRange[3] + tempY };
3916
                        foreach (double[] range in containRanges)
3917
                        {
3918
                            if (SPPIDUtil.IsOverlap(range, movedRange))
3919
                            {
3920
                                result = false;
3921
                                break;
3922
                            }
3923
                        }
3924

    
3925
                        if (result)
3926
                        {
3927
                            //double tempDistance = Utils.CalcDistance(new double[] { 0, 0, 0 }, new double[] { tempX, tempY, 0 });
3928
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(0, 0, tempX, tempY);
3929
                            bool bChange = false;
3930
                            if (distance > tempDistance)
3931
                                bChange = true;
3932
                            else if (distance.Equals(tempDistance) && (movePointX.Equals(0d) || movePointY.Equals(0d)))
3933
                                bChange = true;
3934

    
3935
                            if (bChange)
3936
                            {
3937
                                distance = tempDistance;
3938
                                movePointX = tempX;
3939
                                movePointY = tempY;
3940
                            }
3941
                        }
3942
                    }
3943

    
3944
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3945
            if (dependency != null)
3946
            {
3947
                radApp.ActiveSelectSet.RemoveAll();
3948
                radApp.ActiveSelectSet.Add(dependency);
3949
                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3950
                transform.DefineByMove2d(movePointX, movePointY);
3951
                radApp.ActiveSelectSet.Transform(transform, true);
3952
                radApp.ActiveSelectSet.RemoveAll();
3953
            }
3954
        }
3955

    
3956
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3957
        {
3958
            LMConnector targetConnector = null;
3959
            Symbol targetSymbol = targetObj as Symbol;
3960
            Symbol connectedSymbol = connectedObj as Symbol;
3961
            Line targetLine = targetObj as Line;
3962
            Line connectedLine = connectedObj as Line;
3963
            if (targetSymbol != null && connectedSymbol != null)
3964
            {
3965
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3966
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3967

    
3968
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3969
                {
3970
                    if (connector.get_ItemStatus() != "Active")
3971
                        continue;
3972

    
3973
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3974
                    {
3975
                        targetConnector = connector;
3976
                        break;
3977
                    }
3978
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3979
                    {
3980
                        targetConnector = connector;
3981
                        break;
3982
                    }
3983
                }
3984

    
3985
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3986
                {
3987
                    if (connector.get_ItemStatus() != "Active")
3988
                        continue;
3989

    
3990
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3991
                    {
3992
                        targetConnector = connector;
3993
                        break;
3994
                    }
3995
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3996
                    {
3997
                        targetConnector = connector;
3998
                        break;
3999
                    }
4000
                }
4001

    
4002
                ReleaseCOMObjects(targetLMSymbol);
4003
                ReleaseCOMObjects(connectedLMSymbol);
4004
            }
4005
            else if (targetLine != null && connectedLine != null)
4006
            {
4007
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4008
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4009

    
4010
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
4011
                {
4012
                    foreach (LMRepresentation rep in targetModelItem.Representations)
4013
                    {
4014
                        if (targetConnector != null)
4015
                            break;
4016

    
4017
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4018
                        {
4019
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4020

    
4021
                            if (IsConnected(_LMConnector, connectedModelItem))
4022
                                targetConnector = _LMConnector;
4023
                            else
4024
                                ReleaseCOMObjects(_LMConnector);
4025
                        }
4026
                    }
4027

    
4028
                    ReleaseCOMObjects(targetModelItem);
4029
                }
4030
            }
4031
            else
4032
            {
4033
                LMSymbol connectedLMSymbol = null;
4034
                if (connectedSymbol != null)
4035
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
4036
                else if (targetSymbol != null)
4037
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
4038
                else
4039
                {
4040

    
4041
                }
4042
                LMModelItem targetModelItem = null;
4043
                if (targetLine != null)
4044
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
4045
                else if (connectedLine != null)
4046
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
4047
                else
4048
                {
4049

    
4050
                }
4051
                if (connectedLMSymbol != null && targetModelItem != null)
4052
                {
4053
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
4054
                    {
4055
                        if (connector.get_ItemStatus() != "Active")
4056
                            continue;
4057

    
4058
                        if (IsConnected(connector, targetModelItem))
4059
                        {
4060
                            targetConnector = connector;
4061
                            break;
4062
                        }
4063
                    }
4064

    
4065
                    if (targetConnector == null)
4066
                    {
4067
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
4068
                        {
4069
                            if (connector.get_ItemStatus() != "Active")
4070
                                continue;
4071

    
4072
                            if (IsConnected(connector, targetModelItem))
4073
                            {
4074
                                targetConnector = connector;
4075
                                break;
4076
                            }
4077
                        }
4078
                    }
4079
                }
4080

    
4081
            }
4082

    
4083
            return targetConnector;
4084
        }
4085

    
4086
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
4087
        {
4088
            double[] result = null;
4089
            Line targetLine = targetObj as Line;
4090
            Symbol targetSymbol = targetObj as Symbol;
4091
            Line connLine = connObj as Line;
4092
            Symbol connSymbol = connObj as Symbol;
4093
            location = SegmentLocation.None;
4094
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
4095
            {
4096
                result = GetConnectorVertices(targetConnector)[0];
4097
                if (targetSymbol != null && connSymbol != null)
4098
                {
4099
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
4100
                    result = new double[] { result[0], result[1] };
4101
                    if (slopeType == SlopeType.HORIZONTAL)
4102
                        location = SegmentLocation.Up;
4103
                    else if (slopeType == SlopeType.VERTICAL)
4104
                        location = SegmentLocation.Right;
4105
                }
4106
                else if (targetLine != null)
4107
                {
4108
                    result = new double[] { result[0], result[1] };
4109
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4110
                        location = SegmentLocation.Up;
4111
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
4112
                        location = SegmentLocation.Right;
4113
                }
4114
                else if (connLine != null)
4115
                {
4116
                    result = new double[] { result[0], result[1] };
4117
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
4118
                        location = SegmentLocation.Up;
4119
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
4120
                        location = SegmentLocation.Right;
4121
                }
4122
            }
4123
            else
4124
            {
4125
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
4126
                {
4127
                    Line line = connObj as Line;
4128
                    LMConnector connectedConnector = null;
4129
                    int connIndex = 0;
4130
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4131
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
4132

    
4133
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
4134

    
4135
                    ReleaseCOMObjects(modelItem);
4136
                    ReleaseCOMObjects(connectedConnector);
4137

    
4138
                    if (vertices.Count > 0)
4139
                    {
4140
                        if (connIndex == 1)
4141
                            result = vertices[0];
4142
                        else if (connIndex == 2)
4143
                            result = vertices[vertices.Count - 1];
4144

    
4145
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4146
                        {
4147
                            result = new double[] { result[0], result[1] };
4148
                            location = SegmentLocation.Up;
4149
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4150
                                location = location | SegmentLocation.Right;
4151
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4152
                                location = location | SegmentLocation.Left;
4153
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4154
                                location = location | SegmentLocation.Left;
4155
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4156
                                location = location | SegmentLocation.Right;
4157
                        }
4158
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
4159
                        {
4160
                            result = new double[] { result[0], result[1] };
4161
                            location = SegmentLocation.Right;
4162
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4163
                                location = location | SegmentLocation.Up;
4164
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4165
                                location = location | SegmentLocation.Down;
4166
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4167
                                location = location | SegmentLocation.Down;
4168
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4169
                                location = location | SegmentLocation.Up;
4170
                        }
4171

    
4172
                    }
4173
                }
4174
                else
4175
                {
4176
                    Log.Write("error in GetSegemtPoint");
4177
                }
4178
            }
4179

    
4180
            return result;
4181
        }
4182

    
4183
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
4184
        {
4185
            bool result = false;
4186

    
4187
            foreach (LMRepresentation rep in modelItem.Representations)
4188
            {
4189
                if (result)
4190
                    break;
4191

    
4192
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4193
                {
4194
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4195

    
4196
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4197
                        connector.ConnectItem1SymbolObject != null &&
4198
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4199
                    {
4200
                        result = true;
4201
                        ReleaseCOMObjects(_LMConnector);
4202
                        break;
4203
                    }
4204
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4205
                        connector.ConnectItem2SymbolObject != null &&
4206
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4207
                    {
4208
                        result = true;
4209
                        ReleaseCOMObjects(_LMConnector);
4210
                        break;
4211
                    }
4212
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4213
                        connector.ConnectItem1SymbolObject != null &&
4214
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4215
                    {
4216
                        result = true;
4217
                        ReleaseCOMObjects(_LMConnector);
4218
                        break;
4219
                    }
4220
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4221
                        connector.ConnectItem2SymbolObject != null &&
4222
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4223
                    {
4224
                        result = true;
4225
                        ReleaseCOMObjects(_LMConnector);
4226
                        break;
4227
                    }
4228

    
4229
                    ReleaseCOMObjects(_LMConnector);
4230
                }
4231
            }
4232

    
4233

    
4234
            return result;
4235
        }
4236

    
4237
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
4238
        {
4239
            foreach (LMRepresentation rep in modelItem.Representations)
4240
            {
4241
                if (connectedConnector != null)
4242
                    break;
4243

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

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

    
4281
                    if (connectedConnector == null)
4282
                        ReleaseCOMObjects(_LMConnector);
4283
                }
4284
            }
4285
        }
4286

    
4287
        /// <summary>
4288
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
4289
        /// </summary>
4290
        /// <param name="modelItemID1"></param>
4291
        /// <param name="modelItemID2"></param>
4292
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
4293
        {
4294
            try
4295
            {
4296
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
4297
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
4298
                List<double[]> vertices1 = null;
4299
                string graphicOID1 = string.Empty;
4300
                if (connector1 != null)
4301
                {
4302
                    vertices1 = GetConnectorVertices(connector1);
4303
                    graphicOID1 = connector1.get_GraphicOID();
4304
                }
4305
                _LMAItem item1 = modelItem1.AsLMAItem();
4306
                ReleaseCOMObjects(connector1);
4307
                connector1 = null;
4308

    
4309
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
4310
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
4311
                List<double[]> vertices2 = null;
4312
                string graphicOID2 = string.Empty;
4313
                if (connector2 != null)
4314
                {
4315
                    vertices2 = GetConnectorVertices(connector2);
4316
                    graphicOID2 = connector2.get_GraphicOID();
4317
                }
4318
                _LMAItem item2 = modelItem2.AsLMAItem();
4319
                ReleaseCOMObjects(connector2);
4320
                connector2 = null;
4321

    
4322

    
4323
                ISPClientData3.ISPItem ispItem1 = item1.ISPItem;
4324
                ISPClientData3.ISPItemType ispItemType1 = ispItem1.get_ItemType();
4325
                foreach (ISPClientData3.ISPAttribute attrib in ispItem1.get_Attributes())
4326
                {
4327
                    if (attrib.AttName == "PipeRunType")
4328
                    {
4329
                        string aa = attrib.Value;
4330
                    }
4331
                }
4332

    
4333

    
4334
                ISPClientData3.ISPItem ispItem2 = item2.ISPItem;
4335
                ISPClientData3.ISPItemType ispItemType2 = ispItem2.get_ItemType();
4336
                foreach (ISPClientData3.ISPAttribute attrib in ispItem2.get_Attributes())
4337
                {
4338
                    if (attrib.AttName == "PipeRunType")
4339
                    {
4340
                        string aa = attrib.Value;
4341
                    }
4342
                }
4343

    
4344

    
4345
                // item2가 item1으로 조인
4346
                _placement.PIDJoinRuns(ref item1, ref item2);
4347
                item1.Commit();
4348
                item2.Commit();
4349

    
4350
                string beforeID = string.Empty;
4351
                string afterID = string.Empty;
4352

    
4353
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
4354
                {
4355
                    beforeID = modelItem2.Id;
4356
                    afterID = modelItem1.Id;
4357
                    survivorId = afterID;
4358
                }
4359
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
4360
                {
4361
                    beforeID = modelItem1.Id;
4362
                    afterID = modelItem2.Id;
4363
                    survivorId = afterID;
4364
                }
4365
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
4366
                {
4367
                    int model1Cnt = GetConnectorCount(modelId1);
4368
                    int model2Cnt = GetConnectorCount(modelId2);
4369
                    if (model1Cnt == 0)
4370
                    {
4371
                        beforeID = modelItem1.Id;
4372
                        afterID = modelItem2.Id;
4373
                        survivorId = afterID;
4374
                    }
4375
                    else if (model2Cnt == 0)
4376
                    {
4377
                        beforeID = modelItem2.Id;
4378
                        afterID = modelItem1.Id;
4379
                        survivorId = afterID;
4380
                    }
4381
                    else
4382
                        survivorId = null;
4383
                }
4384
                else
4385
                {
4386
                    Log.Write("잘못된 경우");
4387
                    survivorId = null;
4388
                }
4389

    
4390
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
4391
                {
4392
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
4393
                    foreach (var line in lines)
4394
                        line.SPPID.ModelItemId = afterID;
4395
                }
4396

    
4397
                ReleaseCOMObjects(modelItem1);
4398
                ReleaseCOMObjects(item1);
4399
                ReleaseCOMObjects(modelItem2);
4400
                ReleaseCOMObjects(item2);
4401
            }
4402
            catch (Exception ex)
4403
            {
4404
                Log.Write("Join Error");
4405
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
4406
            }
4407
        }
4408
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
4409
        {
4410
            bool result = false;
4411
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
4412
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
4413
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
4414

    
4415
            foreach (var item in endBreaks)
4416
            {
4417
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
4418
                {
4419
                    result = true;
4420
                    break;
4421
                }
4422
            }
4423

    
4424
            return result;
4425
        }
4426
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
4427
        {
4428
            List<string> temp = new List<string>();
4429
            List<LMConnector> connectors = new List<LMConnector>();
4430
            foreach (LMConnector connector in symbol.Avoid1Connectors)
4431
            {
4432
                if (connector.get_ItemStatus() != "Active")
4433
                    continue;
4434

    
4435
                LMModelItem modelItem = connector.ModelItemObject;
4436
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4437
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4438
                    temp.Add(modelItem.Id);
4439

    
4440
                if (temp.Contains(modelItem.Id) &&
4441
                    connOtherSymbol != null &&
4442
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4443
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4444
                    temp.Remove(modelItem.Id);
4445

    
4446

    
4447
                if (temp.Contains(modelItem.Id))
4448
                    connectors.Add(connector);
4449
                ReleaseCOMObjects(connOtherSymbol);
4450
                connOtherSymbol = null;
4451
                ReleaseCOMObjects(modelItem);
4452
                modelItem = null;
4453
            }
4454

    
4455
            foreach (LMConnector connector in symbol.Avoid2Connectors)
4456
            {
4457
                if (connector.get_ItemStatus() != "Active")
4458
                    continue;
4459

    
4460
                LMModelItem modelItem = connector.ModelItemObject;
4461
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4462
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4463
                    temp.Add(modelItem.Id);
4464

    
4465
                if (temp.Contains(modelItem.Id) &&
4466
                    connOtherSymbol != null &&
4467
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4468
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4469
                    temp.Remove(modelItem.Id);
4470

    
4471
                if (temp.Contains(modelItem.Id))
4472
                    connectors.Add(connector);
4473
                ReleaseCOMObjects(connOtherSymbol);
4474
                connOtherSymbol = null;
4475
                ReleaseCOMObjects(modelItem);
4476
                modelItem = null;
4477
            }
4478

    
4479

    
4480
            List<string> result = new List<string>();
4481
            string originalName = GetSPPIDFileName(modelId);
4482
            foreach (var connector in connectors)
4483
            {
4484
                string fileName = GetSPPIDFileName(connector.ModelItemID);
4485
                if (originalName == fileName)
4486
                    result.Add(connector.ModelItemID);
4487
                else
4488
                {
4489
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
4490
                        result.Add(connector.ModelItemID);
4491
                    else
4492
                    {
4493
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
4494
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
4495
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
4496
                            result.Add(connector.ModelItemID);
4497
                    }
4498
                }
4499
            }
4500

    
4501
            foreach (var connector in connectors)
4502
                ReleaseCOMObjects(connector);
4503

    
4504
            return result;
4505

    
4506

    
4507
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
4508
            {
4509
                LMSymbol findResult = null;
4510
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
4511
                    findResult = connector.ConnectItem1SymbolObject;
4512
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
4513
                    findResult = connector.ConnectItem2SymbolObject;
4514

    
4515
                return findResult;
4516
            }
4517
        }
4518

    
4519
        /// <summary>
4520
        /// PipeRun의 좌표를 가져오는 메서드
4521
        /// </summary>
4522
        /// <param name="modelId"></param>
4523
        /// <returns></returns>
4524
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
4525
        {
4526
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
4527
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
4528

    
4529
            if (modelItem != null)
4530
            {
4531
                foreach (LMRepresentation rep in modelItem.Representations)
4532
                {
4533
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4534
                    {
4535
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4536
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
4537
                        {
4538
                            ReleaseCOMObjects(_LMConnector);
4539
                            _LMConnector = null;
4540
                            continue;
4541
                        }
4542
                        connectorVertices.Add(_LMConnector, new List<double[]>());
4543
                        dynamic OID = rep.get_GraphicOID().ToString();
4544
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4545
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4546
                        int verticesCount = lineStringGeometry.VertexCount;
4547
                        double[] vertices = null;
4548
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
4549
                        for (int i = 0; i < verticesCount; i++)
4550
                        {
4551
                            double x = 0;
4552
                            double y = 0;
4553
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4554
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
4555
                        }
4556
                    }
4557
                }
4558

    
4559
                ReleaseCOMObjects(modelItem);
4560
            }
4561

    
4562
            return connectorVertices;
4563
        }
4564

    
4565
        private List<double[]> GetConnectorVertices(LMConnector connector)
4566
        {
4567
            List<double[]> vertices = new List<double[]>();
4568
            if (connector != null)
4569
            {
4570
                dynamic OID = connector.get_GraphicOID().ToString();
4571
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4572
                if (drawingObject != null)
4573
                {
4574
                    Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4575
                    int verticesCount = lineStringGeometry.VertexCount;
4576
                    double[] value = null;
4577
                    lineStringGeometry.GetVertices(ref verticesCount, ref value);
4578
                    for (int i = 0; i < verticesCount; i++)
4579
                    {
4580
                        double x = 0;
4581
                        double y = 0;
4582
                        lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4583
                        vertices.Add(new double[] { x, y });
4584
                    }
4585
                }
4586
            }
4587
            return vertices;
4588
        }
4589

    
4590
        private double GetConnectorDistance(LMConnector connector)
4591
        {
4592
            double result = 0;
4593
            List<double[]> vertices = new List<double[]>();
4594
            if (connector != null)
4595
            {
4596
                dynamic OID = connector.get_GraphicOID().ToString();
4597
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4598
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4599
                int verticesCount = lineStringGeometry.VertexCount;
4600
                double[] value = null;
4601
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4602
                for (int i = 0; i < verticesCount; i++)
4603
                {
4604
                    double x = 0;
4605
                    double y = 0;
4606
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4607
                    vertices.Add(new double[] { x, y });
4608
                    if (vertices.Count > 1)
4609
                    {
4610
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
4611
                    }
4612
                }
4613
            }
4614
            return result;
4615
        }
4616
        private double[] GetConnectorRange(LMConnector connector)
4617
        {
4618
            double[] result = null;
4619
            List<double[]> vertices = new List<double[]>();
4620
            if (connector != null)
4621
            {
4622
                dynamic OID = connector.get_GraphicOID().ToString();
4623
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4624
                double minX = 0;
4625
                double minY = 0;
4626
                double maxX = 0;
4627
                double maxY = 0;
4628

    
4629
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
4630
                result = new double[] { minX, minY, maxX, maxY };
4631
            }
4632
            return result;
4633
        }
4634
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
4635
        {
4636
            List<double[]> vertices = null;
4637
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
4638
            if (drawingObject != null)
4639
            {
4640
                vertices = new List<double[]>();
4641
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4642
                int verticesCount = lineStringGeometry.VertexCount;
4643
                double[] value = null;
4644
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4645
                for (int i = 0; i < verticesCount; i++)
4646
                {
4647
                    double x = 0;
4648
                    double y = 0;
4649
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4650
                    vertices.Add(new double[] { x, y });
4651
                }
4652
            }
4653
            return vertices;
4654
        }
4655
        /// <summary>
4656
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
4657
        /// </summary>
4658
        /// <param name="connectorVertices"></param>
4659
        /// <param name="connX"></param>
4660
        /// <param name="connY"></param>
4661
        /// <returns></returns>
4662
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
4663
        {
4664
            double length = double.MaxValue;
4665
            LMConnector targetConnector = null;
4666
            foreach (var item in connectorVertices)
4667
            {
4668
                List<double[]> points = item.Value;
4669
                for (int i = 0; i < points.Count - 1; i++)
4670
                {
4671
                    double[] point1 = points[i];
4672
                    double[] point2 = points[i + 1];
4673
                    double x1 = Math.Min(point1[0], point2[0]);
4674
                    double y1 = Math.Min(point1[1], point2[1]);
4675
                    double x2 = Math.Max(point1[0], point2[0]);
4676
                    double y2 = Math.Max(point1[1], point2[1]);
4677

    
4678
                    if ((x1 <= connX && x2 >= connX) ||
4679
                        (y1 <= connY && y2 >= connY))
4680
                    {
4681
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
4682
                        if (length >= distance)
4683
                        {
4684
                            targetConnector = item.Key;
4685
                            length = distance;
4686
                        }
4687

    
4688
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
4689
                        if (length >= distance)
4690
                        {
4691
                            targetConnector = item.Key;
4692
                            length = distance;
4693
                        }
4694
                    }
4695
                }
4696
            }
4697

    
4698
            // 못찾았을때.
4699
            length = double.MaxValue;
4700
            if (targetConnector == null)
4701
            {
4702
                foreach (var item in connectorVertices)
4703
                {
4704
                    List<double[]> points = item.Value;
4705

    
4706
                    foreach (double[] point in points)
4707
                    {
4708
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
4709
                        if (length >= distance)
4710
                        {
4711
                            targetConnector = item.Key;
4712
                            length = distance;
4713
                        }
4714
                    }
4715
                }
4716
            }
4717

    
4718
            return targetConnector;
4719
        }
4720

    
4721
        private LMConnector FindTargetLMConnectorForBranch(Line currentLine, Line targetLine, ref double x, ref double y)
4722
        {
4723
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4724
            if (vertices.Count == 0)
4725
                return null;
4726

    
4727
            double length = double.MaxValue;
4728
            LMConnector targetConnector = null;
4729
            double[] resultPoint = null;
4730
            List<double[]> targetVertices = null;
4731

    
4732
            // Vertices 포인트에 제일 가까운곳
4733
            foreach (var item in vertices)
4734
            {
4735
                List<double[]> points = item.Value;
4736
                for (int i = 0; i < points.Count; i++)
4737
                {
4738
                    double[] point = points[i];
4739
                    double tempX = point[0];
4740
                    double tempY = point[1];
4741

    
4742
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4743
                    if (length >= distance)
4744
                    {
4745
                        targetConnector = item.Key;
4746
                        length = distance;
4747
                        resultPoint = point;
4748
                        targetVertices = item.Value;
4749
                    }
4750
                }
4751
            }
4752

    
4753
            // Vertices Cross에 제일 가까운곳
4754
            foreach (var item in vertices)
4755
            {
4756
                List<double[]> points = item.Value;
4757
                for (int i = 0; i < points.Count - 1; i++)
4758
                {
4759
                    double[] point1 = points[i];
4760
                    double[] point2 = points[i + 1];
4761

    
4762
                    double maxLineX = Math.Max(point1[0], point2[0]);
4763
                    double minLineX = Math.Min(point1[0], point2[0]);
4764
                    double maxLineY = Math.Max(point1[1], point2[1]);
4765
                    double minLineY = Math.Min(point1[1], point2[1]);
4766

    
4767
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4768

    
4769
                    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]);
4770
                    if (crossingPoint != null)
4771
                    {
4772
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4773
                        if (length >= distance)
4774
                        {
4775
                            if (slope == SlopeType.Slope &&
4776
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4777
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4778
                            {
4779
                                targetConnector = item.Key;
4780
                                length = distance;
4781
                                resultPoint = crossingPoint;
4782
                                targetVertices = item.Value;
4783
                            }
4784
                            else if (slope == SlopeType.HORIZONTAL &&
4785
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4786
                            {
4787
                                targetConnector = item.Key;
4788
                                length = distance;
4789
                                resultPoint = crossingPoint;
4790
                                targetVertices = item.Value;
4791
                            }
4792
                            else if (slope == SlopeType.VERTICAL &&
4793
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4794
                            {
4795
                                targetConnector = item.Key;
4796
                                length = distance;
4797
                                resultPoint = crossingPoint;
4798
                                targetVertices = item.Value;
4799
                            }
4800
                        }
4801
                    }
4802
                }
4803
            }
4804

    
4805
            foreach (var item in vertices)
4806
                if (item.Key != null && item.Key != targetConnector)
4807
                    ReleaseCOMObjects(item.Key);
4808

    
4809
            if (SPPIDUtil.IsBranchLine(currentLine, targetLine))
4810
            {
4811
                double tempResultX = resultPoint[0];
4812
                double tempResultY = resultPoint[1];
4813
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4814

    
4815
                GridSetting gridSetting = GridSetting.GetInstance();
4816
                for (int i = 0; i < targetVertices.Count; i++)
4817
                {
4818
                    double[] point = targetVertices[i];
4819
                    double tempX = targetVertices[i][0];
4820
                    double tempY = targetVertices[i][1];
4821
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4822
                    if (tempX == tempResultX && tempY == tempResultY)
4823
                    {
4824
                        if (i == 0)
4825
                        {
4826
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4827
                            bool containZeroLength = false;
4828
                            if (connSymbol != null)
4829
                            {
4830
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4831
                                {
4832
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4833
                                        containZeroLength = true;
4834
                                }
4835
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4836
                                {
4837
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4838
                                        containZeroLength = true;
4839
                                }
4840
                            }
4841

    
4842
                            if (connSymbol == null ||
4843
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4844
                                containZeroLength)
4845
                            {
4846
                                bool bCalcX = false;
4847
                                bool bCalcY = false;
4848
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4849
                                    bCalcX = true;
4850
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4851
                                    bCalcY = true;
4852
                                else
4853
                                {
4854
                                    bCalcX = true;
4855
                                    bCalcY = true;
4856
                                }
4857

    
4858
                                if (bCalcX)
4859
                                {
4860
                                    double nextX = targetVertices[i + 1][0];
4861
                                    double newX = 0;
4862
                                    if (nextX > tempX)
4863
                                    {
4864
                                        newX = tempX + gridSetting.Length;
4865
                                        if (newX > nextX)
4866
                                            newX = (point[0] + nextX) / 2;
4867
                                    }
4868
                                    else
4869
                                    {
4870
                                        newX = tempX - gridSetting.Length;
4871
                                        if (newX < nextX)
4872
                                            newX = (point[0] + nextX) / 2;
4873
                                    }
4874
                                    resultPoint = new double[] { newX, resultPoint[1] };
4875
                                }
4876

    
4877
                                if (bCalcY)
4878
                                {
4879
                                    double nextY = targetVertices[i + 1][1];
4880
                                    double newY = 0;
4881
                                    if (nextY > tempY)
4882
                                    {
4883
                                        newY = tempY + gridSetting.Length;
4884
                                        if (newY > nextY)
4885
                                            newY = (point[1] + nextY) / 2;
4886
                                    }
4887
                                    else
4888
                                    {
4889
                                        newY = tempY - gridSetting.Length;
4890
                                        if (newY < nextY)
4891
                                            newY = (point[1] + nextY) / 2;
4892
                                    }
4893
                                    resultPoint = new double[] { resultPoint[0], newY };
4894
                                }
4895
                            }
4896
                        }
4897
                        else if (i == targetVertices.Count - 1 && targetVertices.Count != 2)
4898
                        {
4899
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4900
                            bool containZeroLength = false;
4901
                            if (connSymbol != null)
4902
                            {
4903
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4904
                                {
4905
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4906
                                        containZeroLength = true;
4907
                                }
4908
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4909
                                {
4910
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4911
                                        containZeroLength = true;
4912
                                }
4913
                            }
4914

    
4915
                            if (connSymbol == null ||
4916
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4917
                                containZeroLength)
4918
                            {
4919
                                bool bCalcX = false;
4920
                                bool bCalcY = false;
4921
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4922
                                    bCalcX = true;
4923
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4924
                                    bCalcY = true;
4925
                                else
4926
                                {
4927
                                    bCalcX = true;
4928
                                    bCalcY = true;
4929
                                }
4930

    
4931
                                if (bCalcX)
4932
                                {
4933
                                    double nextX = targetVertices[i - 1][0];
4934
                                    double newX = 0;
4935
                                    if (nextX > tempX)
4936
                                    {
4937
                                        newX = tempX + gridSetting.Length;
4938
                                        if (newX > nextX)
4939
                                            newX = (point[0] + nextX) / 2;
4940
                                    }
4941
                                    else
4942
                                    {
4943
                                        newX = tempX - gridSetting.Length;
4944
                                        if (newX < nextX)
4945
                                            newX = (point[0] + nextX) / 2;
4946
                                    }
4947
                                    resultPoint = new double[] { newX, resultPoint[1] };
4948
                                }
4949

    
4950
                                if (bCalcY)
4951
                                {
4952
                                    double nextY = targetVertices[i - 1][1];
4953
                                    double newY = 0;
4954
                                    if (nextY > tempY)
4955
                                    {
4956
                                        newY = tempY + gridSetting.Length;
4957
                                        if (newY > nextY)
4958
                                            newY = (point[1] + nextY) / 2;
4959
                                    }
4960
                                    else
4961
                                    {
4962
                                        newY = tempY - gridSetting.Length;
4963
                                        if (newY < nextY)
4964
                                            newY = (point[1] + nextY) / 2;
4965
                                    }
4966
                                    resultPoint = new double[] { resultPoint[0], newY };
4967
                                }
4968
                            }
4969
                        }
4970
                        break;
4971
                    }
4972
                }
4973
            }
4974

    
4975
            x = resultPoint[0];
4976
            y = resultPoint[1];
4977

    
4978
            return targetConnector;
4979
        }
4980

    
4981
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4982
        {
4983
            LMConnector result = null;
4984
            List<LMConnector> connectors = new List<LMConnector>();
4985
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4986

    
4987
            if (modelItem != null)
4988
            {
4989
                foreach (LMRepresentation rep in modelItem.Representations)
4990
                {
4991
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4992
                        connectors.Add(dataSource.GetConnector(rep.Id));
4993
                }
4994

    
4995
                ReleaseCOMObjects(modelItem);
4996
            }
4997

    
4998
            if (connectors.Count == 1)
4999
                result = connectors[0];
5000
            else
5001
                foreach (var item in connectors)
5002
                    ReleaseCOMObjects(item);
5003

    
5004
            return result;
5005
        }
5006

    
5007
        private LMConnector GetLMConnectorFirst(string modelItemID)
5008
        {
5009
            LMConnector result = null;
5010
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5011

    
5012
            if (modelItem != null)
5013
            {
5014
                foreach (LMRepresentation rep in modelItem.Representations)
5015
                {
5016
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" &&
5017
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
5018
                    {
5019
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5020
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
5021
                        {
5022
                            result = connector;
5023
                            break;
5024
                        }
5025
                        else
5026
                        {
5027
                            ReleaseCOMObjects(connector);
5028
                            connector = null;
5029
                        }
5030
                    }
5031
                }
5032
                ReleaseCOMObjects(modelItem);
5033
                modelItem = null;
5034
            }
5035

    
5036
            return result;
5037
        }
5038

    
5039
        private int GetConnectorCount(string modelItemID)
5040
        {
5041
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5042
            int result = 0;
5043
            if (modelItem != null)
5044
            {
5045
                foreach (LMRepresentation rep in modelItem.Representations)
5046
                {
5047
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5048
                        result++;
5049
                    ReleaseCOMObjects(rep);
5050
                }
5051
                ReleaseCOMObjects(modelItem);
5052
            }
5053

    
5054
            return result;
5055
        }
5056

    
5057
        public List<string> GetRepresentations(string modelItemID)
5058
        {
5059
            List<string> result = new List<string>(); ;
5060
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
5061
            if (modelItem != null)
5062
            {
5063
                foreach (LMRepresentation rep in modelItem.Representations)
5064
                {
5065
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5066
                        result.Add(rep.Id);
5067
                }
5068
                ReleaseCOMObjects(modelItem);
5069
            }
5070

    
5071
            return result;
5072
        }
5073

    
5074
        private void LineNumberModeling(LineNumber lineNumber)
5075
        {
5076
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5077
            if (line != null)
5078
            {
5079
                double x = 0;
5080
                double y = 0;
5081
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
5082

    
5083
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5084
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
5085
                if (connectedLMConnector != null)
5086
                {
5087
                    Array points = new double[] { 0, x, y };
5088
                    lineNumber.SPPID.SPPID_X = x;
5089
                    lineNumber.SPPID.SPPID_Y = y;
5090
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
5091

    
5092
                    if (_LmLabelPresist != null)
5093
                    {
5094
                        _LmLabelPresist.Commit();
5095
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
5096
                        ReleaseCOMObjects(_LmLabelPresist);
5097
                    }
5098
                }
5099

    
5100
                foreach (var item in connectorVertices)
5101
                    ReleaseCOMObjects(item.Key);
5102
            }
5103
        }
5104
        private void LineNumberCorrectModeling(LineNumber lineNumber)
5105
        {
5106
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
5107
            if (line == null || line.SPPID.Vertices == null)
5108
                return;
5109

    
5110
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
5111
            {
5112
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
5113
                if (removeLabel != null)
5114
                {
5115
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
5116
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
5117

    
5118
                    GridSetting gridSetting = GridSetting.GetInstance();
5119
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
5120

    
5121
                    double[] labelRange = null;
5122
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
5123
                    List<double[]> vertices = GetConnectorVertices(connector);
5124

    
5125
                    double[] resultStart = null;
5126
                    double[] resultEnd = null;
5127
                    double distance = double.MaxValue;
5128
                    for (int i = 0; i < vertices.Count - 1; i++)
5129
                    {
5130
                        double[] startPoint = vertices[i];
5131
                        double[] endPoint = vertices[i + 1];
5132
                        foreach (var item in line.SPPID.Vertices)
5133
                        {
5134
                            double[] lineStartPoint = item[0];
5135
                            double[] lineEndPoint = item[item.Count - 1];
5136

    
5137
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
5138
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
5139
                            if (tempDistance < distance)
5140
                            {
5141
                                distance = tempDistance;
5142
                                resultStart = startPoint;
5143
                                resultEnd = endPoint;
5144
                            }
5145
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
5146
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
5147
                            if (tempDistance < distance)
5148
                            {
5149
                                distance = tempDistance;
5150
                                resultStart = startPoint;
5151
                                resultEnd = endPoint;
5152
                            }
5153
                        }
5154
                    }
5155

    
5156
                    if (resultStart != null && resultEnd != null)
5157
                    {
5158
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
5159
                        double lineStartX = 0;
5160
                        double lineStartY = 0;
5161
                        double lineEndX = 0;
5162
                        double lineEndY = 0;
5163
                        double lineNumberX = 0;
5164
                        double lineNumberY = 0;
5165
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
5166
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
5167

    
5168
                        double lineX = (lineStartX + lineEndX) / 2;
5169
                        double lineY = (lineStartY + lineEndY) / 2;
5170
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
5171
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
5172

    
5173
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
5174
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
5175
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
5176
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
5177

    
5178
                        double offsetX = 0;
5179
                        double offsetY = 0;
5180
                        if (slope == SlopeType.HORIZONTAL)
5181
                        {
5182
                            // Line Number 아래
5183
                            if (lineY < lineNumberY)
5184
                            {
5185
                                offsetX = labelCenterX - SPPIDCenterX;
5186
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
5187
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5188
                            }
5189
                            // Line Number 위
5190
                            else
5191
                            {
5192
                                offsetX = labelCenterX - SPPIDCenterX;
5193
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
5194
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5195
                            }
5196
                        }
5197
                        else if (slope == SlopeType.VERTICAL)
5198
                        {
5199
                            // Line Number 오르쪽
5200
                            if (lineX < lineNumberX)
5201
                            {
5202
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
5203
                                offsetY = labelCenterY - SPPIDCenterY;
5204
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5205
                            }
5206
                            // Line Number 왼쪽
5207
                            else
5208
                            {
5209
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
5210
                                offsetY = labelCenterY - SPPIDCenterY;
5211
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5212
                            }
5213
                        }
5214

    
5215
                        if (offsetY != 0 || offsetY != 0)
5216
                        {
5217
                            if (connector.ConnectItem1SymbolObject != null &&
5218
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
5219
                            {
5220
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
5221

    
5222
                                double x1, y1, x2, y2, originX, originY;
5223
                                symbol.Range(out x1, out y1, out x2, out y2);
5224
                                symbol.GetOrigin(out originX, out originY);
5225
                                if (originX < lineNumber.SPPID.SPPID_X)
5226
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5227
                                else
5228
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5229
                            }
5230
                            else if (connector.ConnectItem2SymbolObject != null &&
5231
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
5232
                            {
5233
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
5234

    
5235
                                double x1, y1, x2, y2, originX, originY;
5236
                                symbol.Range(out x1, out y1, out x2, out y2);
5237
                                symbol.GetOrigin(out originX, out originY);
5238
                                if (originX < lineNumber.SPPID.SPPID_X)
5239
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5240
                                else
5241
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5242
                            }
5243

    
5244
                            radApp.ActiveSelectSet.RemoveAll();
5245
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
5246
                            if (dependency != null)
5247
                            {
5248
                                radApp.ActiveSelectSet.Add(dependency);
5249
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
5250
                                transform.DefineByMove2d(-offsetX, -offsetY);
5251
                                radApp.ActiveSelectSet.Transform(transform, true);
5252
                                radApp.ActiveSelectSet.RemoveAll();
5253
                            }
5254
                        }
5255

    
5256
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
5257
                        {
5258
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
5259
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
5260
                        }
5261
                    }
5262

    
5263

    
5264
                    ReleaseCOMObjects(connector);
5265
                    connector = null;
5266
                }
5267

    
5268
                ReleaseCOMObjects(removeLabel);
5269
                removeLabel = null;
5270
            }
5271
        }
5272
        /// <summary>
5273
        /// Flow Mark Modeling
5274
        /// </summary>
5275
        /// <param name="line"></param>
5276
        private void FlowMarkModeling(Line line)
5277
        {
5278
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
5279
            {
5280
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
5281
                if (connector != null)
5282
                {
5283
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
5284
                    List<double[]> vertices = GetConnectorVertices(connector);
5285
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
5286
                    double[] point = vertices[vertices.Count - 1];
5287
                    Array array = new double[] { 0, point[0], point[1] };
5288
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, null, null, LabeledItem: connector.AsLMRepresentation());
5289
                    if (_LMLabelPersist != null)
5290
                    {
5291
                        _LMLabelPersist.Commit();
5292
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
5293
                        ReleaseCOMObjects(_LMLabelPersist);
5294
                    }
5295
                }
5296
            }
5297
        }
5298

    
5299
        /// <summary>
5300
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
5301
        /// </summary>
5302
        /// <param name="lineNumber"></param>
5303
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
5304
        {
5305
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
5306
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
5307
            {
5308
                if (a.ATTRIBUTE == "Tag Seq No")
5309
                    return 1;
5310
                else if (b.ATTRIBUTE == "Tag Seq No")
5311
                    return -1;
5312

    
5313
                return 0;
5314
            }
5315

    
5316
            foreach (LineRun run in lineNumber.RUNS)
5317
            {
5318
                foreach (var item in run.RUNITEMS)
5319
                {
5320
                    if (item.GetType() == typeof(Line))
5321
                    {
5322
                        Line line = item as Line;
5323
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
5324
                        {
5325
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5326
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5327
                            {
5328
                                foreach (var attribute in lineNumber.ATTRIBUTES)
5329
                                {
5330
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
5331
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5332
                                    {
5333
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5334
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
5335
                                        {
5336
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5337
                                            if (_FluidSystemAttribute != null)
5338
                                            {
5339
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
5340
                                                if (dt.Rows.Count == 1)
5341
                                                {
5342
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5343
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5344
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5345
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5346
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5347

    
5348
                                                    if (_LMAAttribute != null)
5349
                                                    {
5350
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5351
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5352
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
5353
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5354
                                                    }
5355
                                                }
5356
                                                if (dt != null)
5357
                                                    dt.Dispose();
5358
                                            }
5359
                                        }
5360
                                        else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(attribute.VALUE) && _LMAAttribute != null)
5361
                                        {
5362
                                            DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", attribute.VALUE));
5363

    
5364
                                            if (rows.Length.Equals(1))
5365
                                            {
5366
                                                if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5367
                                                    attribute.VALUE = rows[0]["MetricStr"].ToString();
5368
                                                else
5369
                                                    attribute.VALUE = rows[0]["InchStr"].ToString();
5370

    
5371
                                                if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5372
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5373
                                                else if (_LMAAttribute.get_Value() != attribute.VALUE)
5374
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5375
                                            }
5376
                                        }
5377
                                        else if (_LMAAttribute != null)
5378
                                        {
5379
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5380
                                                _LMAAttribute.set_Value(attribute.VALUE);
5381
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
5382
                                                _LMAAttribute.set_Value(attribute.VALUE);
5383
                                        }
5384
                                    }
5385
                                }
5386
                                _LMModelItem.Commit();
5387
                            }
5388
                            if (_LMModelItem != null)
5389
                                ReleaseCOMObjects(_LMModelItem);
5390
                            endLine.Add(line.SPPID.ModelItemId);
5391
                        }
5392
                    }
5393
                }
5394
            }
5395
        }
5396

    
5397
        /// <summary>
5398
        /// Symbol Attribute 입력 메서드
5399
        /// </summary>
5400
        /// <param name="item"></param>
5401
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
5402
        {
5403
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
5404
            string sRep = null;
5405
            string sModelID = null;
5406
            if (targetItem.GetType() == typeof(Symbol))
5407
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
5408
            else if (targetItem.GetType() == typeof(Equipment))
5409
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
5410
            else if (targetItem.GetType() == typeof(Line))
5411
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
5412

    
5413
            if (!string.IsNullOrEmpty(sRep))
5414
            {
5415
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
5416
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
5417
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5418

    
5419
                foreach (var item in targetAttributes)
5420
                {
5421
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5422
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5423
                    {
5424
                        if (!mapping.IsText)
5425
                        {
5426
                            LMAAttribute _LMAAttribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5427
                            if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5428
                            {
5429
                                DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5430

    
5431
                                if (rows.Length.Equals(1))
5432
                                {
5433
                                    if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5434
                                        item.VALUE = rows[0]["MetricStr"].ToString();
5435
                                    else
5436
                                        item.VALUE = rows[0]["InchStr"].ToString();
5437

    
5438
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5439
                                        _LMAAttribute.set_Value(item.VALUE);
5440
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5441
                                        _LMAAttribute.set_Value(item.VALUE);
5442
                                }
5443
                            }
5444
                            else if (_LMAAttribute != null)
5445
                            {
5446
                                _LMAAttribute.set_Value(item.VALUE);
5447
                                // OPC 일경우 Attribute 저장
5448
                                if (targetItem.GetType() == typeof(Symbol))
5449
                                {
5450
                                    Symbol symbol = targetItem as Symbol;
5451
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
5452
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
5453
                                }
5454
                            }
5455
                        }
5456
                        else
5457
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
5458
                    }
5459
                }
5460
                _LMModelItem.Commit();
5461

    
5462
                ReleaseCOMObjects(_Attributes);
5463
                ReleaseCOMObjects(_LMModelItem);
5464
                ReleaseCOMObjects(_LMSymbol);
5465
            }
5466
            else if (!string.IsNullOrEmpty(sModelID))
5467
            {
5468
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
5469
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5470

    
5471
                foreach (var item in targetAttributes)
5472
                {
5473
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5474
                    if (mapping == null)
5475
                        continue;
5476

    
5477
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5478
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
5479
                    {
5480
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5481
                        if (_FluidSystemAttribute != null)
5482
                        {
5483
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
5484
                            if (dt.Rows.Count == 1)
5485
                            {
5486
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5487
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5488
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5489
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5490
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5491

    
5492
                                if (_LMAAttribute != null)
5493
                                {
5494
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5495
                                        _LMAAttribute.set_Value(item.VALUE);
5496
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5497
                                        _LMAAttribute.set_Value(item.VALUE);
5498
                                }
5499
                            }
5500
                            if (dt != null)
5501
                                dt.Dispose();
5502
                        }
5503
                    }
5504
                    else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5505
                    {
5506
                        DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5507

    
5508
                        if (rows.Length.Equals(1))
5509
                        {
5510
                            if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5511
                                item.VALUE = rows[0]["MetricStr"].ToString();
5512
                            else
5513
                                item.VALUE = rows[0]["InchStr"].ToString();
5514

    
5515
                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5516
                                _LMAAttribute.set_Value(item.VALUE);
5517
                            else if (_LMAAttribute.get_Value() != item.VALUE)
5518
                                _LMAAttribute.set_Value(item.VALUE);
5519
                        }
5520
                    }
5521
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5522
                    {
5523
                        if (!mapping.IsText)
5524
                        {
5525
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5526
                            if (_Attribute != null)
5527
                                _Attribute.set_Value(item.VALUE);
5528
                        }
5529
                    }
5530
                }
5531
                _LMModelItem.Commit();
5532

    
5533
                ReleaseCOMObjects(_Attributes);
5534
                ReleaseCOMObjects(_LMModelItem);
5535
            }
5536
        }
5537

    
5538
        /// <summary>
5539
        /// Input SpecBreak Attribute
5540
        /// </summary>
5541
        /// <param name="specBreak"></param>
5542
        private void InputSpecBreakAttribute(SpecBreak specBreak)
5543
        {
5544
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
5545
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
5546

    
5547
            if (upStreamObj != null &&
5548
                downStreamObj != null)
5549
            {
5550
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
5551

    
5552
                if (targetLMConnector != null)
5553
                {
5554
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
5555
                    {
5556
                        string symbolPath = _LMLabelPersist.get_FileName();
5557
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
5558
                        if (mapping != null)
5559
                        {
5560
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
5561
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5562
                            {
5563
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
5564
                                if (values.Length == 2)
5565
                                {
5566
                                    string upStreamValue = values[0];
5567
                                    string downStreamValue = values[1];
5568

    
5569
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
5570
                                }
5571
                            }
5572
                        }
5573
                    }
5574

    
5575
                    ReleaseCOMObjects(targetLMConnector);
5576
                }
5577
            }
5578

    
5579

    
5580
            #region 내부에서만 쓰는 메서드
5581
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
5582
            {
5583
                Symbol upStreamSymbol = _upStreamObj as Symbol;
5584
                Line upStreamLine = _upStreamObj as Line;
5585
                Symbol downStreamSymbol = _downStreamObj as Symbol;
5586
                Line downStreamLine = _downStreamObj as Line;
5587
                // 둘다 Line일 경우
5588
                if (upStreamLine != null && downStreamLine != null)
5589
                {
5590
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5591
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5592
                }
5593
                // 둘다 Symbol일 경우
5594
                else if (upStreamSymbol != null && downStreamSymbol != null)
5595
                {
5596
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
5597
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5598
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5599

    
5600
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5601
                    {
5602
                        if (connector.get_ItemStatus() != "Active")
5603
                            continue;
5604

    
5605
                        if (connector.Id != zeroLenthConnector.Id)
5606
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5607
                    }
5608

    
5609
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5610
                    {
5611
                        if (connector.get_ItemStatus() != "Active")
5612
                            continue;
5613

    
5614
                        if (connector.Id != zeroLenthConnector.Id)
5615
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5616
                    }
5617

    
5618
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5619
                    {
5620
                        if (connector.get_ItemStatus() != "Active")
5621
                            continue;
5622

    
5623
                        if (connector.Id != zeroLenthConnector.Id)
5624
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5625
                    }
5626

    
5627
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5628
                    {
5629
                        if (connector.get_ItemStatus() != "Active")
5630
                            continue;
5631

    
5632
                        if (connector.Id != zeroLenthConnector.Id)
5633
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5634
                    }
5635

    
5636
                    ReleaseCOMObjects(zeroLenthConnector);
5637
                    ReleaseCOMObjects(upStreamLMSymbol);
5638
                    ReleaseCOMObjects(downStreamLMSymbol);
5639
                }
5640
                else if (upStreamSymbol != null && downStreamLine != null)
5641
                {
5642
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
5643
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5644
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5645

    
5646
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5647
                    {
5648
                        if (connector.get_ItemStatus() != "Active")
5649
                            continue;
5650

    
5651
                        if (connector.Id == zeroLenthConnector.Id)
5652
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5653
                    }
5654

    
5655
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5656
                    {
5657
                        if (connector.get_ItemStatus() != "Active")
5658
                            continue;
5659

    
5660
                        if (connector.Id == zeroLenthConnector.Id)
5661
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5662
                    }
5663

    
5664
                    ReleaseCOMObjects(zeroLenthConnector);
5665
                    ReleaseCOMObjects(upStreamLMSymbol);
5666
                }
5667
                else if (upStreamLine != null && downStreamSymbol != null)
5668
                {
5669
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
5670
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5671
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5672

    
5673
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5674
                    {
5675
                        if (connector.get_ItemStatus() != "Active")
5676
                            continue;
5677

    
5678
                        if (connector.Id == zeroLenthConnector.Id)
5679
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5680
                    }
5681

    
5682
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5683
                    {
5684
                        if (connector.get_ItemStatus() != "Active")
5685
                            continue;
5686

    
5687
                        if (connector.Id == zeroLenthConnector.Id)
5688
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5689
                    }
5690

    
5691
                    ReleaseCOMObjects(zeroLenthConnector);
5692
                    ReleaseCOMObjects(downStreamLMSymbol);
5693
                }
5694
            }
5695

    
5696
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
5697
            {
5698
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5699
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5700
                {
5701
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5702
                    if (_LMAAttribute != null)
5703
                    {
5704
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5705
                            _LMAAttribute.set_Value(value);
5706
                        else if (_LMAAttribute.get_Value() != value)
5707
                            _LMAAttribute.set_Value(value);
5708
                    }
5709

    
5710
                    _LMModelItem.Commit();
5711
                }
5712
                if (_LMModelItem != null)
5713
                    ReleaseCOMObjects(_LMModelItem);
5714
            }
5715

    
5716
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
5717
            {
5718
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
5719
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5720
                {
5721
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5722
                    if (_LMAAttribute != null)
5723
                    {
5724
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5725
                            _LMAAttribute.set_Value(value);
5726
                        else if (_LMAAttribute.get_Value() != value)
5727
                            _LMAAttribute.set_Value(value);
5728
                    }
5729

    
5730
                    _LMModelItem.Commit();
5731
                }
5732
                if (_LMModelItem != null)
5733
                    ReleaseCOMObjects(_LMModelItem);
5734
            }
5735
            #endregion
5736
        }
5737

    
5738
        private void InputEndBreakAttribute(EndBreak endBreak)
5739
        {
5740
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5741
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5742

    
5743
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
5744
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
5745
            {
5746
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
5747
                if (labelPersist != null)
5748
                {
5749
                    LMRepresentation representation = labelPersist.RepresentationObject;
5750
                    if (representation != null)
5751
                    {
5752
                        LMConnector connector = dataSource.GetConnector(representation.Id);
5753
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
5754
                        string modelItemID = connector.ModelItemID;
5755
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
5756
                        {
5757
                            List<string> modelItemIDs = new List<string>();
5758
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5759
                            {
5760
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
5761
                                foreach (LMConnector item in symbol.Connect1Connectors)
5762
                                {
5763
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5764
                                        modelItemIDs.Add(item.ModelItemID);
5765
                                    ReleaseCOMObjects(item);
5766
                                }
5767
                                foreach (LMConnector item in symbol.Connect2Connectors)
5768
                                {
5769
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5770
                                        modelItemIDs.Add(item.ModelItemID);
5771
                                    ReleaseCOMObjects(item);
5772
                                }
5773
                                ReleaseCOMObjects(symbol);
5774
                                symbol = null;
5775
                            }
5776
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5777
                            {
5778
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
5779
                                foreach (LMConnector item in symbol.Connect1Connectors)
5780
                                {
5781
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5782
                                        modelItemIDs.Add(item.ModelItemID);
5783
                                    ReleaseCOMObjects(item);
5784
                                }
5785
                                foreach (LMConnector item in symbol.Connect2Connectors)
5786
                                {
5787
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5788
                                        modelItemIDs.Add(item.ModelItemID);
5789
                                    ReleaseCOMObjects(item);
5790
                                }
5791
                                ReleaseCOMObjects(symbol);
5792
                                symbol = null;
5793
                            }
5794

    
5795
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5796
                            if (modelItemIDs.Count == 1)
5797
                            {
5798
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5799
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5800
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5801
                                {
5802
                                    bool result = false;
5803
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5804
                                    {
5805
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5806
                                            result = true;
5807
                                        ReleaseCOMObjects(loop);
5808
                                    }
5809

    
5810
                                    if (result)
5811
                                    {
5812
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5813
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5814
                                        //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5815
                                        //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5816
                                        ZeroLengthModelItem.Commit();
5817
                                    }
5818
                                    else
5819
                                    {
5820
                                        List<string> loopModelItems = new List<string>();
5821
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5822
                                        {
5823
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5824
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5825
                                            {
5826
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5827
                                                    loopModelItems.Add(loop.ModelItemID);
5828
                                                ReleaseCOMObjects(loop);
5829
                                            }
5830
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5831
                                            {
5832
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5833
                                                    loopModelItems.Add(loop.ModelItemID);
5834
                                                ReleaseCOMObjects(loop);
5835
                                            }
5836
                                            ReleaseCOMObjects(_symbol);
5837
                                            _symbol = null;
5838
                                        }
5839
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5840
                                        {
5841
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5842
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5843
                                            {
5844
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5845
                                                    loopModelItems.Add(loop.ModelItemID);
5846
                                                ReleaseCOMObjects(loop);
5847
                                            }
5848
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5849
                                            {
5850
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5851
                                                    loopModelItems.Add(loop.ModelItemID);
5852
                                                ReleaseCOMObjects(loop);
5853
                                            }
5854
                                            ReleaseCOMObjects(_symbol);
5855
                                            _symbol = null;
5856
                                        }
5857

    
5858
                                        loopModelItems = loopModelItems.Distinct().ToList();
5859
                                        if (loopModelItems.Count == 1)
5860
                                        {
5861
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5862
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5863
                                            //object value2 = loopModelItem.Attributes["SubUnitNumber"].get_Value();
5864
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5865
                                            //modelItem.Attributes["SubUnitNumber"].set_Value(value2);
5866
                                            modelItem.Commit();
5867
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5868
                                            //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5869
                                            ZeroLengthModelItem.Commit();
5870

    
5871
                                            ReleaseCOMObjects(loopModelItem);
5872
                                            loopModelItem = null;
5873
                                        }
5874
                                    }
5875
                                }
5876
                                else
5877
                                {
5878
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5879
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5880
                                    //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5881
                                    //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5882
                                    ZeroLengthModelItem.Commit();
5883
                                }
5884
                                ReleaseCOMObjects(modelItem);
5885
                                modelItem = null;
5886
                                ReleaseCOMObjects(onlyOne);
5887
                                onlyOne = null;
5888
                            }
5889
                        }
5890
                        ReleaseCOMObjects(connector);
5891
                        connector = null;
5892
                        ReleaseCOMObjects(ZeroLengthModelItem);
5893
                        ZeroLengthModelItem = null;
5894
                    }
5895
                    ReleaseCOMObjects(representation);
5896
                    representation = null;
5897
                }
5898
                ReleaseCOMObjects(labelPersist);
5899
                labelPersist = null;
5900
            }
5901
        }
5902

    
5903
        /// <summary>
5904
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5905
        /// </summary>
5906
        /// <param name="text"></param>
5907
        private void NormalTextModeling(Text text)
5908
        {
5909
            LMSymbol _LMSymbol = null;
5910

    
5911
            LMItemNote _LMItemNote = null;
5912
            LMAAttribute _LMAAttribute = null;
5913

    
5914
            double x = 0;
5915
            double y = 0;
5916
            double angle = text.ANGLE;
5917
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5918

    
5919
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5920
            text.SPPID.SPPID_X = x;
5921
            text.SPPID.SPPID_Y = y;
5922

    
5923
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5924
            if (_LMSymbol != null)
5925
            {
5926
                _LMSymbol.Commit();
5927
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5928
                if (_LMItemNote != null)
5929
                {
5930
                    _LMItemNote.Commit();
5931
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5932
                    if (_LMAAttribute != null)
5933
                    {
5934
                        _LMAAttribute.set_Value(text.VALUE);
5935
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5936
                        _LMItemNote.Commit();
5937

    
5938

    
5939
                        double[] range = null;
5940
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5941
                        {
5942
                            double[] temp = null;
5943
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5944
                            if (temp != null)
5945
                            {
5946
                                if (range == null)
5947
                                    range = temp;
5948
                                else
5949
                                {
5950
                                    range = new double[] {
5951
                                            Math.Min(range[0], temp[0]),
5952
                                            Math.Min(range[1], temp[1]),
5953
                                            Math.Max(range[2], temp[2]),
5954
                                            Math.Max(range[3], temp[3])
5955
                                        };
5956
                                }
5957
                            }
5958
                        }
5959
                        text.SPPID.Range = range;
5960

    
5961
                        if (_LMAAttribute != null)
5962
                            ReleaseCOMObjects(_LMAAttribute);
5963
                        if (_LMItemNote != null)
5964
                            ReleaseCOMObjects(_LMItemNote);
5965
                    }
5966

    
5967
                    TextCorrectModeling(text);
5968
                }
5969
            }
5970
            if (_LMSymbol != null)
5971
                ReleaseCOMObjects(_LMSymbol);
5972
        }
5973

    
5974
        private void DefaultTextModeling(string value, double x, double y)
5975
        {
5976
            LMSymbol _LMSymbol = null;
5977

    
5978
            LMItemNote _LMItemNote = null;
5979
            LMAAttribute _LMAAttribute = null;
5980

    
5981
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5982
            if (_LMSymbol != null)
5983
            {
5984
                _LMSymbol.Commit();
5985
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5986
                if (_LMItemNote != null)
5987
                {
5988
                    _LMItemNote.Commit();
5989
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5990
                    if (_LMAAttribute != null)
5991
                    {
5992
                        _LMAAttribute.set_Value(value);
5993
                        _LMItemNote.Commit();
5994

    
5995
                        if (_LMAAttribute != null)
5996
                            ReleaseCOMObjects(_LMAAttribute);
5997
                        if (_LMItemNote != null)
5998
                            ReleaseCOMObjects(_LMItemNote);
5999
                    }
6000
                }
6001
            }
6002
            if (_LMSymbol != null)
6003
                ReleaseCOMObjects(_LMSymbol);
6004
        }
6005

    
6006
        private void AssociationTextModeling(Text text)
6007
        {
6008
            LMSymbol _LMSymbol = null;
6009
            LMConnector connectedLMConnector = null;
6010
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6011
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
6012
            {
6013
                Symbol symbol = owner as Symbol;
6014
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6015
                if (_LMSymbol != null)
6016
                {
6017
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6018
                    {
6019
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6020
                        {
6021
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6022

    
6023
                            if (mapping != null)
6024
                            {
6025
                                double x = 0;
6026
                                double y = 0;
6027

    
6028
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6029
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6030
                                Array array = new double[] { 0, x, y };
6031
                                text.SPPID.SPPID_X = x;
6032
                                text.SPPID.SPPID_Y = y;
6033
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6034
                                if (_LMLabelPersist != null)
6035
                                {
6036
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6037
                                    _LMLabelPersist.Commit();
6038
                                    ReleaseCOMObjects(_LMLabelPersist);
6039
                                }
6040
                            }
6041
                        }
6042
                    }
6043
                }
6044
            }
6045
            else if (owner != null && owner.GetType() == typeof(Line))
6046
            {
6047
                Line line = owner as Line;
6048
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
6049
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
6050

    
6051
                if (connectedLMConnector != null)
6052
                {
6053
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
6054
                    {
6055
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6056
                        {
6057
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6058

    
6059
                            if (mapping != null)
6060
                            {
6061
                                double x = 0;
6062
                                double y = 0;
6063
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
6064
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6065
                                Array array = new double[] { 0, x, y };
6066

    
6067
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6068
                                if (_LMLabelPersist != null)
6069
                                {
6070
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6071
                                    _LMLabelPersist.Commit();
6072

    
6073
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
6074
                                    if (dependency != null)
6075
                                    {
6076
                                        radApp.ActiveSelectSet.RemoveAll();
6077
                                        radApp.ActiveSelectSet.Add(dependency);
6078
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
6079
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
6080
                                        radApp.ActiveSelectSet.Transform(transform, true);
6081
                                        radApp.ActiveSelectSet.RemoveAll();
6082
                                    }
6083

    
6084
                                    ReleaseCOMObjects(_LMLabelPersist);
6085
                                }
6086
                            }
6087
                        }
6088
                    }
6089
                }
6090
            }
6091
            if (_LMSymbol != null)
6092
                ReleaseCOMObjects(_LMSymbol);
6093
        }
6094

    
6095
        private void TextCorrectModeling(Text text)
6096
        {
6097
            if (text.SPPID.Range == null)
6098
                return;
6099

    
6100
            bool needRemodeling = false;
6101
            bool loop = true;
6102
            GridSetting gridSetting = GridSetting.GetInstance();
6103
            while (loop)
6104
            {
6105
                loop = false;
6106
                foreach (var overlapText in document.TEXTINFOS)
6107
                {
6108
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
6109
                        continue;
6110

    
6111
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
6112
                    {
6113
                        double percentX = 0;
6114
                        double percentY = 0;
6115
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
6116
                        {
6117
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
6118
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
6119
                        }
6120
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
6121
                        {
6122
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
6123
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
6124
                        }
6125

    
6126
                        double tempX = 0;
6127
                        double tempY = 0;
6128
                        bool overlapX = false;
6129
                        bool overlapY = false;
6130
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6131
                        if (percentX >= percentY)
6132
                        {
6133
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6134
                            double move = gridSetting.Length * count;
6135
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
6136
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
6137
                            needRemodeling = true;
6138
                            loop = true;
6139
                        }
6140
                        else
6141
                        {
6142
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6143
                            double move = gridSetting.Length * count;
6144
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
6145
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
6146
                            needRemodeling = true;
6147
                            loop = true;
6148
                        }
6149
                    }
6150
                }
6151
            }
6152

    
6153

    
6154
            if (needRemodeling)
6155
            {
6156
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
6157
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6158
                text.SPPID.RepresentationId = null;
6159

    
6160
                LMItemNote _LMItemNote = null;
6161
                LMAAttribute _LMAAttribute = null;
6162
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
6163
                if (_LMSymbol != null)
6164
                {
6165
                    _LMSymbol.Commit();
6166
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6167
                    if (_LMItemNote != null)
6168
                    {
6169
                        _LMItemNote.Commit();
6170
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6171
                        if (_LMAAttribute != null)
6172
                        {
6173
                            _LMAAttribute.set_Value(text.VALUE);
6174
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6175
                            _LMItemNote.Commit();
6176

    
6177
                            ReleaseCOMObjects(_LMAAttribute);
6178
                            ReleaseCOMObjects(_LMItemNote);
6179
                        }
6180
                    }
6181
                }
6182

    
6183
                ReleaseCOMObjects(symbol);
6184
                symbol = null;
6185
                ReleaseCOMObjects(_LMItemNote);
6186
                _LMItemNote = null;
6187
                ReleaseCOMObjects(_LMAAttribute);
6188
                _LMAAttribute = null;
6189
                ReleaseCOMObjects(_LMSymbol);
6190
                _LMSymbol = null;
6191
            }
6192
        }
6193

    
6194
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
6195
        {
6196
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
6197
            {
6198
                List<Text> allTexts = new List<Text>();
6199
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6200
                LMRepresentation representation = targetLabel.RepresentationObject;
6201
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
6202
                if (targetLabel.RepresentationObject != null && symbol != null)
6203
                {
6204
                    double[] symbolRange = null;
6205
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
6206
                    if (symbolRange != null)
6207
                    {
6208
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
6209
                        {
6210
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
6211
                            if (findText != null)
6212
                            {
6213
                                double[] range = null;
6214
                                GetSPPIDSymbolRange(labelPersist, ref range);
6215
                                findText.SPPID.Range = range;
6216
                                allTexts.Add(findText);
6217
                            }
6218

    
6219
                            ReleaseCOMObjects(labelPersist);
6220
                        }
6221

    
6222
                        if (allTexts.Count > 0)
6223
                        {
6224
                            #region Sort Text By Y
6225
                            allTexts.Sort(SortTextByY);
6226
                            int SortTextByY(Text a, Text b)
6227
                            {
6228
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
6229
                            }
6230
                            #endregion
6231

    
6232
                            #region 정렬하기전 방향
6233
                            List<Text> left = new List<Text>();
6234
                            List<Text> down = new List<Text>();
6235
                            List<Text> right = new List<Text>();
6236
                            List<Text> up = new List<Text>();
6237
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
6238
                            foreach (var loopText in allTexts)
6239
                            {
6240
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
6241
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
6242
                                double originX = 0;
6243
                                double originY = 0;
6244
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6245
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6246

    
6247
                                if (angle < 45)
6248
                                {
6249
                                    // Text 오른쪽
6250
                                    if (textCenterX > originX)
6251
                                        right.Add(loopText);
6252
                                    // Text 왼쪽
6253
                                    else
6254
                                        left.Add(loopText);
6255
                                }
6256
                                else
6257
                                {
6258
                                    // Text 아래쪽
6259
                                    if (textCenterY > originY)
6260
                                        down.Add(loopText);
6261
                                    // Text 위쪽
6262
                                    else
6263
                                        up.Add(loopText);
6264
                                }
6265
                            }
6266

    
6267
                            #endregion
6268

    
6269
                            foreach (var texts in sortTexts)
6270
                            {
6271
                                if (texts.Count == 0)
6272
                                    continue;
6273

    
6274
                                #region 첫번째 Text로 기준 맞춤
6275
                                for (int i = 0; i < texts.Count; i++)
6276
                                {
6277
                                    if (i != 0)
6278
                                    {
6279
                                        Text currentText = texts[i];
6280
                                        Text prevText = texts[i - 1];
6281
                                        double minY = prevText.SPPID.Range[1];
6282
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
6283
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
6284
                                        double _gapX = centerX - centerPrevX;
6285
                                        double _gapY = currentText.SPPID.Range[3] - minY;
6286
                                        MoveText(currentText, _gapX, _gapY);
6287
                                    }
6288
                                }
6289
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
6290
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
6291
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
6292
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
6293
                                rangeMinX.Sort();
6294
                                rangeMinY.Sort();
6295
                                rangeMaxX.Sort();
6296
                                rangeMaxY.Sort();
6297
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
6298
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
6299
                                #endregion
6300
                                #region 정렬
6301
                                Text correctBySymbol = texts[0];
6302
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
6303
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
6304
                                double originX = 0;
6305
                                double originY = 0;
6306
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6307
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6308
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
6309
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
6310

    
6311
                                double gapX = 0;
6312
                                double gapY = 0;
6313
                                if (angle < 45)
6314
                                {
6315
                                    // Text 오른쪽
6316
                                    if (textCenterX > originX)
6317
                                    {
6318
                                        gapX = rangeMinX[0] - symbolRange[2];
6319
                                        gapY = allTextCenterY - symbolCenterY;
6320
                                    }
6321
                                    // Text 왼쪽
6322
                                    else
6323
                                    {
6324
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
6325
                                        gapY = allTextCenterY - symbolCenterY;
6326
                                    }
6327
                                }
6328
                                else
6329
                                {
6330
                                    // Text 아래쪽
6331
                                    if (textCenterY > originY)
6332
                                    {
6333
                                        gapX = allTextCenterX - symbolCenterX;
6334
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
6335
                                    }
6336
                                    // Text 위쪽
6337
                                    else
6338
                                    {
6339
                                        gapX = allTextCenterX - symbolCenterX;
6340
                                        gapY = rangeMinY[0] - symbolRange[3];
6341
                                    }
6342
                                }
6343

    
6344
                                foreach (var item in texts)
6345
                                {
6346
                                    MoveText(item, gapX, gapY);
6347
                                    RemodelingAssociationText(item);
6348
                                }
6349
                                #endregion
6350
                            }
6351
                        }
6352
                    }
6353
                }
6354

    
6355
                void MoveText(Text moveText, double x, double y)
6356
                {
6357
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
6358
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
6359
                    moveText.SPPID.Range = new double[] {
6360
                        moveText.SPPID.Range[0] - x,
6361
                        moveText.SPPID.Range[1]- y,
6362
                        moveText.SPPID.Range[2]- x,
6363
                        moveText.SPPID.Range[3]- y
6364
                    };
6365
                }
6366

    
6367
                endTexts.AddRange(allTexts);
6368

    
6369
                ReleaseCOMObjects(targetLabel);
6370
                targetLabel = null;
6371
                ReleaseCOMObjects(representation);
6372
                representation = null;
6373
            }
6374
        }
6375

    
6376
        private void RemodelingAssociationText(Text text)
6377
        {
6378
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6379
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
6380
            removeLabel.Commit();
6381
            ReleaseCOMObjects(removeLabel);
6382
            removeLabel = null;
6383

    
6384
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6385
            if (owner != null && owner.GetType() == typeof(Symbol))
6386
            {
6387
                Symbol symbol = owner as Symbol;
6388
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6389
                if (_LMSymbol != null)
6390
                {
6391
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
6392
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6393
                    {
6394
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6395

    
6396
                        if (mapping != null)
6397
                        {
6398
                            double x = 0;
6399
                            double y = 0;
6400

    
6401
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
6402
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6403
                            if (_LMLabelPersist != null)
6404
                            {
6405
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6406
                                _LMLabelPersist.Commit();
6407
                            }
6408
                            ReleaseCOMObjects(_LMLabelPersist);
6409
                            _LMLabelPersist = null;
6410
                        }
6411
                    }
6412
                }
6413
                ReleaseCOMObjects(_LMSymbol);
6414
                _LMSymbol = null;
6415
            }
6416
        }
6417

    
6418
        /// <summary>
6419
        /// Note Modeling
6420
        /// </summary>
6421
        /// <param name="note"></param>
6422
        private void NoteModeling(Note note, List<Note> correctList)
6423
        {
6424
            LMSymbol _LMSymbol = null;
6425
            LMItemNote _LMItemNote = null;
6426
            LMAAttribute _LMAAttribute = null;
6427

    
6428
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
6429
            {
6430
                double x = 0;
6431
                double y = 0;
6432

    
6433
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
6434
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6435
                note.SPPID.SPPID_X = x;
6436
                note.SPPID.SPPID_Y = y;
6437

    
6438
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
6439
                if (_LMSymbol != null)
6440
                {
6441
                    _LMSymbol.Commit();
6442
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6443
                    if (_LMItemNote != null)
6444
                    {
6445
                        _LMItemNote.Commit();
6446
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6447
                        if (_LMAAttribute != null)
6448
                        {
6449
                            _LMAAttribute.set_Value(note.VALUE);
6450
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6451

    
6452
                            double[] range = null;
6453
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6454
                            {
6455
                                double[] temp = null;
6456
                                GetSPPIDSymbolRange(labelPersist, ref temp);
6457
                                if (temp != null)
6458
                                {
6459
                                    if (range == null)
6460
                                        range = temp;
6461
                                    else
6462
                                    {
6463
                                        range = new double[] {
6464
                                            Math.Min(range[0], temp[0]),
6465
                                            Math.Min(range[1], temp[1]),
6466
                                            Math.Max(range[2], temp[2]),
6467
                                            Math.Max(range[3], temp[3])
6468
                                        };
6469
                                    }
6470
                                }
6471
                            }
6472
                            if (range != null)
6473
                                correctList.Add(note);
6474
                            note.SPPID.Range = range;
6475

    
6476

    
6477
                            _LMItemNote.Commit();
6478
                        }
6479
                    }
6480
                }
6481
            }
6482

    
6483
            if (_LMAAttribute != null)
6484
                ReleaseCOMObjects(_LMAAttribute);
6485
            if (_LMItemNote != null)
6486
                ReleaseCOMObjects(_LMItemNote);
6487
            if (_LMSymbol != null)
6488
                ReleaseCOMObjects(_LMSymbol);
6489
        }
6490

    
6491
        private void NoteCorrectModeling(Note note, List<Note> endList)
6492
        {
6493
            bool needRemodeling = false;
6494
            bool loop = true;
6495
            GridSetting gridSetting = GridSetting.GetInstance();
6496
            while (loop)
6497
            {
6498
                loop = false;
6499
                foreach (var overlap in endList)
6500
                {
6501
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
6502
                    {
6503
                        double tempX = 0;
6504
                        double tempY = 0;
6505
                        bool overlapX = false;
6506
                        bool overlapY = false;
6507
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6508
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
6509
                        if (overlapY && angle >= 45)
6510
                        {
6511
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6512
                            double move = gridSetting.Length * count;
6513
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
6514
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
6515
                            needRemodeling = true;
6516
                            loop = true;
6517
                        }
6518
                        if (overlapX && angle <= 45)
6519
                        {
6520
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6521
                            double move = gridSetting.Length * count;
6522
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
6523
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
6524
                            needRemodeling = true;
6525
                            loop = true;
6526
                        }
6527
                    }
6528
                }
6529
            }
6530

    
6531

    
6532
            if (needRemodeling)
6533
            {
6534
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
6535
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6536
                note.SPPID.RepresentationId = null;
6537

    
6538
                LMItemNote _LMItemNote = null;
6539
                LMAAttribute _LMAAttribute = null;
6540
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
6541
                if (_LMSymbol != null)
6542
                {
6543
                    _LMSymbol.Commit();
6544
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6545
                    if (_LMItemNote != null)
6546
                    {
6547
                        _LMItemNote.Commit();
6548
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6549
                        if (_LMAAttribute != null)
6550
                        {
6551
                            _LMAAttribute.set_Value(note.VALUE);
6552
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6553
                            _LMItemNote.Commit();
6554

    
6555
                            ReleaseCOMObjects(_LMAAttribute);
6556
                            ReleaseCOMObjects(_LMItemNote);
6557
                        }
6558
                    }
6559
                }
6560

    
6561
                ReleaseCOMObjects(symbol);
6562
                symbol = null;
6563
                ReleaseCOMObjects(_LMItemNote);
6564
                _LMItemNote = null;
6565
                ReleaseCOMObjects(_LMAAttribute);
6566
                _LMAAttribute = null;
6567
                ReleaseCOMObjects(_LMSymbol);
6568
                _LMSymbol = null;
6569
            }
6570

    
6571
            endList.Add(note);
6572
        }
6573

    
6574
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
6575
        {
6576
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6577
            if (modelItem != null)
6578
            {
6579
                foreach (LMRepresentation rep in modelItem.Representations)
6580
                {
6581
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
6582
                    {
6583
                        LMConnector connector = dataSource.GetConnector(rep.Id);
6584
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
6585
                        {
6586
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
6587
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6588
                            if (modelItemIds.Count == 1)
6589
                            {
6590
                                string joinModelItemId = modelItemIds[0];
6591
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6592
                                if (survivorId != null)
6593
                                    break;
6594
                            }
6595
                        }
6596
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
6597
                        {
6598
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
6599
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6600
                            if (modelItemIds.Count == 1)
6601
                            {
6602
                                string joinModelItemId = modelItemIds[0];
6603
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6604
                                if (survivorId != null)
6605
                                    break;
6606
                            }
6607
                        }
6608
                    }
6609
                }
6610
            }
6611
        }
6612

    
6613
        /// <summary>
6614
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
6615
        /// </summary>
6616
        /// <param name="x"></param>
6617
        /// <param name="y"></param>
6618
        /// <param name="originX"></param>
6619
        /// <param name="originY"></param>
6620
        /// <param name="SPPIDLabelLocation"></param>
6621
        /// <param name="location"></param>
6622
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDEtcLocationInfo SPPIDLabelLocation, Location location)
6623
        {
6624
            if (location == Location.None)
6625
            {
6626
                x = originX;
6627
                y = originY;
6628
            }
6629
            else
6630
            {
6631
                if (location.HasFlag(Location.Center))
6632
                {
6633
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
6634
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
6635
                }
6636

    
6637
                if (location.HasFlag(Location.Left))
6638
                    x = SPPIDLabelLocation.X1;
6639
                else if (location.HasFlag(Location.Right))
6640
                    x = SPPIDLabelLocation.X2;
6641

    
6642
                if (location.HasFlag(Location.Down))
6643
                    y = SPPIDLabelLocation.Y1;
6644
                else if (location.HasFlag(Location.Up))
6645
                    y = SPPIDLabelLocation.Y2;
6646
            }
6647
        }
6648

    
6649
        /// <summary>
6650
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
6651
        /// 1. Angle Valve
6652
        /// 2. 3개로 이루어진 Symbol Group
6653
        /// </summary>
6654
        /// <returns></returns>
6655
        private List<Symbol> GetPrioritySymbol()
6656
        {
6657
            DataTable symbolTable = document.SymbolTable;
6658
            // List에 순서대로 쌓는다.
6659
            List<Symbol> symbols = new List<Symbol>();
6660

    
6661
            // Angle Valve 부터
6662
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
6663
            {
6664
                if (!symbols.Contains(symbol))
6665
                {
6666
                    double originX = 0;
6667
                    double originY = 0;
6668

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

    
6673
                    SlopeType slopeType1 = SlopeType.None;
6674
                    SlopeType slopeType2 = SlopeType.None;
6675
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
6676
                    {
6677
                        double connectorX = 0;
6678
                        double connectorY = 0;
6679
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
6680
                        if (slopeType1 == SlopeType.None)
6681
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6682
                        else
6683
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6684
                    }
6685

    
6686
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
6687
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
6688
                        symbols.Add(symbol);
6689
                }
6690
            }
6691

    
6692
            List<Symbol> tempSymbols = new List<Symbol>();
6693
            // Conn 갯수 기준
6694
            foreach (var item in document.SYMBOLS)
6695
            {
6696
                if (!symbols.Contains(item))
6697
                    tempSymbols.Add(item);
6698
            }
6699
            tempSymbols.Sort(SPPIDUtil.SortSymbolPriority);
6700
            symbols.AddRange(tempSymbols);
6701

    
6702
            return symbols;
6703
        }
6704

    
6705
        private void SetPriorityLine(List<Line> lines)
6706
        {
6707
            lines.Sort(SortLinePriority);
6708

    
6709
            int SortLinePriority(Line a, Line b)
6710
            {
6711
                int childRetval = CompareChild(a, b);
6712
                if (childRetval != 0)
6713
                {
6714
                    return childRetval;
6715
                }
6716
                else
6717
                { 
6718
                    // Branch 없는것부터
6719
                    int branchRetval = CompareBranchLine(a, b);
6720
                    if (branchRetval != 0)
6721
                    {
6722
                        return branchRetval;
6723
                    }
6724
                    else
6725
                    {
6726
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
6727
                        int connItemRetval = CompareConnItem(a, b);
6728
                        if (connItemRetval != 0)
6729
                        {
6730
                            return connItemRetval;
6731
                        }
6732
                        else
6733
                        {
6734
                            // line 길이
6735
                            int lengthRetval = CompareLength(a, b);
6736
                            if (lengthRetval != 0)
6737
                            {
6738
                                return lengthRetval;
6739
                            }
6740
                            else
6741
                            {
6742
                                // Symbol 연결 갯수
6743
                                int connSymbolRetval = CompareConnSymbol(a, b);
6744
                                if (connSymbolRetval != 0)
6745
                                {
6746
                                    return connSymbolRetval;
6747
                                }
6748
                                else
6749
                                {
6750
                                    // ConnectedItem이 없는것
6751
                                    int noneConnRetval = CompareNoneConn(a, b);
6752
                                    if (noneConnRetval != 0)
6753
                                    {
6754
                                        return noneConnRetval;
6755
                                    }
6756
                                    else
6757
                                    {
6758

    
6759
                                    }
6760
                                }
6761
                            }
6762
                        }
6763
                    }
6764
                }
6765

    
6766
                return 0;
6767
            }
6768

    
6769
            int CompareChild(Line a, Line b)
6770
            {
6771
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6772
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
6773

    
6774
                // 내림차순
6775
                return countA.CompareTo(countB);
6776
            }
6777

    
6778
            int CompareConnSymbol(Line a, Line b)
6779
            {
6780
                List<Connector> connectorsA = a.CONNECTORS
6781
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6782
                    .ToList();
6783

    
6784
                List<Connector> connectorsB = b.CONNECTORS
6785
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6786
                    .ToList();
6787

    
6788
                // 내림차순
6789
                return connectorsA.Count.CompareTo(connectorsB.Count);
6790
            }
6791

    
6792
            int CompareLength(Line a, Line b)
6793
            {
6794
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6795
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6796

    
6797
                // 오름차순
6798
                return lengthB.CompareTo(lengthA);
6799
            }
6800

    
6801
            int CompareConnItem(Line a, Line b)
6802
            {
6803
                List<Connector> connectorsA = a.CONNECTORS
6804
                    .Where(conn => conn.ConnectedObject != null &&
6805
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6806
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6807
                    .ToList();
6808

    
6809
                List<Connector> connectorsB = b.CONNECTORS
6810
                    .Where(conn => conn.ConnectedObject != null &&
6811
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6812
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6813
                    .ToList();
6814

    
6815
                // 내림차순
6816
                return connectorsA.Count.CompareTo(connectorsB.Count);
6817
            }
6818

    
6819
            int CompareBranchLine(Line a, Line b)
6820
            {
6821
                List<Connector> connectorsA = a.CONNECTORS
6822
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6823
                    .ToList();
6824
                List<Connector> connectorsB = b.CONNECTORS
6825
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6826
                    .ToList();
6827

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

    
6832
            int CompareNoneConn(Line a, Line b)
6833
            {
6834
                List<Connector> connectorsA = a.CONNECTORS
6835
                    .Where(conn => conn.ConnectedObject == null)
6836
                    .ToList();
6837

    
6838
                List<Connector> connectorsB = b.CONNECTORS
6839
                    .Where(conn => conn.ConnectedObject == null)
6840
                    .ToList();
6841

    
6842
                // 내림차순
6843
                return connectorsA.Count.CompareTo(connectorsB.Count);
6844
            }
6845
        }
6846

    
6847
        private void SortText(List<Text> texts)
6848
        {
6849
            texts.Sort(Sort);
6850

    
6851
            int Sort(Text a, Text b)
6852
            {
6853
                int yRetval = CompareY(a, b);
6854
                if (yRetval != 0)
6855
                {
6856
                    return yRetval;
6857
                }
6858
                else
6859
                {
6860
                    return CompareX(a, b);
6861
                }
6862
            }
6863

    
6864
            int CompareY(Text a, Text b)
6865
            {
6866
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6867
            }
6868

    
6869
            int CompareX(Text a, Text b)
6870
            {
6871
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6872
            }
6873
        }
6874
        private void SortNote(List<Note> notes)
6875
        {
6876
            notes.Sort(Sort);
6877

    
6878
            int Sort(Note a, Note b)
6879
            {
6880
                int yRetval = CompareY(a, b);
6881
                if (yRetval != 0)
6882
                {
6883
                    return yRetval;
6884
                }
6885
                else
6886
                {
6887
                    return CompareX(a, b);
6888
                }
6889
            }
6890

    
6891
            int CompareY(Note a, Note b)
6892
            {
6893
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6894
            }
6895

    
6896
            int CompareX(Note a, Note b)
6897
            {
6898
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6899
            }
6900
        }
6901

    
6902
        private void SortBranchLines()
6903
        {
6904
            BranchLines.Sort(SortBranchLine);
6905

    
6906
            int SortBranchLine(Line a, Line b)
6907
            {
6908
                int childRetval = CompareChild(a, b);
6909
                if (childRetval != 0)
6910
                {
6911
                    return childRetval;
6912
                }
6913
                else
6914
                {
6915
                    int branchRetval = CompareChildBranch(a, b);
6916
                    if (branchRetval != 0)
6917
                    {
6918
                        return branchRetval;
6919
                    }
6920
                    else
6921
                    {
6922
                        // line 길이
6923
                        int lengthRetval = CompareLength(a, b);
6924
                        if (lengthRetval != 0)
6925
                        {
6926
                            return lengthRetval;
6927
                        }
6928
                    }
6929
                }
6930
                return 0;
6931
            }
6932

    
6933
            int CompareLength(Line a, Line b)
6934
            {
6935
                double lengthA = Math.Abs(a.SPPID.START_X - a.SPPID.END_X) + Math.Abs(a.SPPID.START_Y - a.SPPID.END_Y);
6936
                double lengthB = Math.Abs(b.SPPID.START_X - b.SPPID.END_X) + Math.Abs(b.SPPID.START_Y - b.SPPID.END_Y);
6937

    
6938
                // 오름차순
6939
                return lengthB.CompareTo(lengthA);
6940
            }
6941

    
6942
            int CompareChildBranch(Line a, Line b)
6943
            {
6944
                int countA = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
6945
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == a));
6946

    
6947
                int countB = document.LINES.Count(c => c.CONNECTORS.Any(n => n.ConnectedObject != null &&
6948
                n.ConnectedObject.GetType() == typeof(Line) && n.ConnectedObject == b));
6949

    
6950
                // 오름차순
6951
                return countB.CompareTo(countA);
6952
            }
6953

    
6954
            int CompareChild(Line a, Line b)
6955
            {
6956
                int countA = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == b);
6957
                int countB = a.CONNECTORS.Count(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Line) && x.ConnectedObject == a);
6958

    
6959
                // 내림차순
6960
                return countA.CompareTo(countB);
6961
            }
6962
        }
6963

    
6964
        private string GetSPPIDFileName(LMModelItem modelItem)
6965
        {
6966
            string symbolPath = null;
6967
            foreach (LMRepresentation rep in modelItem.Representations)
6968
            {
6969
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6970
                {
6971
                    symbolPath = rep.get_FileName();
6972
                    break;
6973
                }
6974
            }
6975
            return symbolPath;
6976
        }
6977

    
6978
        private string GetSPPIDFileName(string modelItemId)
6979
        {
6980
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6981
            string symbolPath = null;
6982
            foreach (LMRepresentation rep in modelItem.Representations)
6983
            {
6984
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6985
                {
6986
                    symbolPath = rep.get_FileName();
6987
                    break;
6988
                }
6989
            }
6990
            ReleaseCOMObjects(modelItem);
6991
            return symbolPath;
6992
        }
6993

    
6994
        /// <summary>
6995
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6996
        /// </summary>
6997
        /// <param name="graphicOID"></param>
6998
        /// <param name="milliseconds"></param>
6999
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
7000
        {
7001
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
7002
            {
7003
                double minX = 0;
7004
                double minY = 0;
7005
                double maxX = 0;
7006
                double maxY = 0;
7007
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
7008
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
7009

    
7010
                Thread.Sleep(milliseconds);
7011
            }
7012
        }
7013

    
7014
        /// <summary>
7015
        /// ComObject를 Release
7016
        /// </summary>
7017
        /// <param name="objVars"></param>
7018
        public void ReleaseCOMObjects(params object[] objVars)
7019
        {
7020
            if (objVars != null)
7021
            {
7022
                int intNewRefCount = 0;
7023
                foreach (object obj in objVars)
7024
                {
7025
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
7026
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
7027
                }
7028
            }
7029
        }
7030

    
7031
        /// IDisposable 구현
7032
        ~AutoModeling()
7033
        {
7034
            this.Dispose(false);
7035
        }
7036

    
7037
        private bool disposed;
7038
        public void Dispose()
7039
        {
7040
            this.Dispose(true);
7041
            GC.SuppressFinalize(this);
7042
        }
7043

    
7044
        protected virtual void Dispose(bool disposing)
7045
        {
7046
            if (this.disposed) return;
7047
            if (disposing)
7048
            {
7049
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
7050
            }
7051
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
7052
            this.disposed = true;
7053
        }
7054
    }
7055
}
클립보드 이미지 추가 (최대 크기: 500 MB)