프로젝트

일반

사용자정보

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

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 919bb48e

이력 | 보기 | 이력해설 | 다운로드 (323 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
                nominalDiameterTable = Project_DB.SelectProjectNominalDiameter();
98
                _placement = new Placement();
99
                dataSource = _placement.PIDDataSource;
100
                
101
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
102
                {
103
                    Log.Write("Start Modeling");
104
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
105
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
106
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 26);
107
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
108

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

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

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

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

    
208
                Log.Write("End Modeling");
209
                radApp.ActiveWindow.Fit();
210

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

    
228
                ReleaseCOMObjects(dataSource);
229
                dataSource = null;
230
                ReleaseCOMObjects(_placement);
231
                _placement = null;
232

    
233
                Thread.Sleep(1000);
234
            }
235
        }
236

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

    
312
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
313
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
314

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

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

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

    
392
                        GridSetting grid = GridSetting.GetInstance();
393
                        int count = grid.DrainValveCellCount;
394
                        double length = grid.Length;
395

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

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

    
453
                                    // 제거
454
                                    RemoveSymbol(connSymbol);
455
                                    RemoveLine(item);
456

    
457
                                    // 재생성
458
                                    SymbolModelingBySymbol(connSymbol);
459
                                    NewLineModeling(item, true);
460
                                }
461
                            }
462

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

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

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

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

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

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

    
638
                LMRelationships relationships = new LMRelationships();
639
                relationships.Collect(dataSource, Filter: filter);
640

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

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

    
800
                    }
801
                }
802
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
803
            }
804

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

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

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

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

    
1048
            }
1049

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

    
1090
            List<SPPIDModel.BulkAttribute> select = _ETCSetting.BulkAttributes.FindAll(x => x.RuleName.Equals(document.BulkAttributeName));
1091
            if (select.Count > 0)
1092
                SPPIDUtil.BulkAttribute(dataSource, select, BulkAttributeItemType.PipeRun);
1093
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1094
            if (select.Count > 0)
1095
                SPPIDUtil.BulkAttribute(dataSource, select, BulkAttributeItemType.Symbol);
1096
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1097
        }
1098
        private void RunGraphicModeling()
1099
        {
1100
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
1101
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Graphic Modeling");
1102
            foreach (var item in document.Graphics)
1103
            {
1104
                try
1105
                {
1106
                    GraphicModeling(item);
1107
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1108
                }
1109
                catch (Exception ex)
1110
                {
1111
                    Log.Write("Error in GrahicModeling");
1112
                    Log.Write("UID : " + item.UID);
1113
                    Log.Write(ex.Message);
1114
                    Log.Write(ex.StackTrace);
1115
                }
1116
            }
1117
        }
1118
        /// <summary>
1119
        /// 도면 생성 메서드
1120
        /// </summary>
1121
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1122
        {
1123
            Log.Write("------------------ Start create document ------------------");
1124
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1125
            Log.Write("Drawing name : " + drawingName);
1126
            Log.Write("Drawing number : " + drawingNumber);
1127
            Thread.Sleep(1000);
1128
            try
1129
            {
1130
                newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1131
            }
1132
            catch (Exception ex)
1133
            {
1134
                if (ex.Message == "Invalid procedure call or argument")
1135
                {
1136
                    Exception newEx = new Exception(string.Format("Invalid Unit [0]", document.Unit), ex.InnerException);
1137
                    throw newEx;
1138
                }
1139
                else
1140
                {
1141
                    throw ex;
1142
                }
1143
            }
1144
            
1145
            if (newDrawing != null)
1146
            {
1147
                document.SPPID_DrawingNumber = drawingNumber;
1148
                document.SPPID_DrawingName = drawingName;
1149
                Thread.Sleep(1000);
1150
                radApp.ActiveWindow.Fit();
1151
                Thread.Sleep(1000);
1152
                radApp.ActiveWindow.Zoom = 2000;
1153
                Thread.Sleep(2000);
1154

    
1155
                //current LMDrawing 가져오기
1156
                LMAFilter filter = new LMAFilter();
1157
                LMACriterion criterion = new LMACriterion();
1158
                filter.ItemType = "Drawing";
1159
                criterion.SourceAttributeName = "Name";
1160
                criterion.Operator = "=";
1161
                criterion.set_ValueAttribute(drawingName);
1162
                filter.get_Criteria().Add(criterion);
1163

    
1164
                LMDrawings drawings = new LMDrawings();
1165
                drawings.Collect(dataSource, Filter: filter);
1166

    
1167
                // Input Drawing Attribute
1168
                LMDrawing drawing = ((dynamic)drawings).Nth(1);
1169
                if (drawing != null)
1170
                {
1171
                    using (DataTable drawingAttributeDT = Project_DB.SelectDrawingProjectAttribute())
1172
                    {
1173
                        foreach (DataRow row in drawingAttributeDT.Rows)
1174
                        {
1175
                            string mappingName = DBNull.Value.Equals(row["SPPID_ATTRIBUTE"]) ? string.Empty : row["SPPID_ATTRIBUTE"].ToString();
1176
                            if (!string.IsNullOrEmpty(mappingName))
1177
                            {
1178
                                string uid = row["UID"].ToString();
1179
                                string name = row["NAME"].ToString();
1180
                                Text text = document.TEXTINFOS.Find(x => x.AREA == uid);
1181
                                if (text != null)
1182
                                {
1183
                                    string value = text.VALUE;
1184
                                    LMAAttribute attribute = drawing.Attributes[mappingName];
1185
                                    if (attribute != null)
1186
                                        attribute.set_Value(value);
1187
                                    ReleaseCOMObjects(attribute);
1188
                                    document.TEXTINFOS.Remove(text);
1189
                                }
1190
                            }
1191
                        }
1192

    
1193
                        drawingAttributeDT.Dispose();
1194
                    }
1195

    
1196
                    ReleaseCOMObjects(drawing);
1197
                }
1198

    
1199
                drawingID = ((dynamic)drawings).Nth(1).Id;
1200
                ReleaseCOMObjects(filter);
1201
                ReleaseCOMObjects(criterion);
1202
                ReleaseCOMObjects(drawings);
1203
                filter = null;
1204
                criterion = null;
1205
                drawings = null;
1206
            }
1207
            else
1208
                Log.Write("Fail Create Drawing");
1209

    
1210
            if (newDrawing != null)
1211
            {
1212
                SetBorderFile();
1213
                return true;
1214
            }
1215
            else
1216
                return false;
1217
        }
1218

    
1219
        private void SetBorderFile()
1220
        {
1221
            ETCSetting setting = ETCSetting.GetInstance();
1222

    
1223
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1224
            {
1225
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1226
                {
1227
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1228
                    {
1229
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1230
                        smartFrame.Update();
1231
                    }
1232

    
1233
                }
1234
            }
1235
        }
1236

    
1237
        /// <summary>
1238
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1239
        /// </summary>
1240
        /// <param name="drawingName"></param>
1241
        /// <param name="drawingNumber"></param>
1242
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1243
        {
1244
            LMDrawings drawings = new LMDrawings();
1245
            drawings.Collect(dataSource);
1246

    
1247
            List<string> drawingNameList = new List<string>();
1248
            List<string> drawingNumberList = new List<string>();
1249

    
1250
            foreach (LMDrawing item in drawings)
1251
            {
1252
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1253
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1254
            }
1255

    
1256
            int nameLength = drawingName.Length;
1257
            while (drawingNameList.Contains(drawingName))
1258
            {
1259
                if (nameLength == drawingName.Length)
1260
                    drawingName += "-1";
1261
                else
1262
                {
1263
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1264
                    drawingName = drawingName.Substring(0, nameLength + 1);
1265
                    drawingName += ++index;
1266
                }
1267
            }
1268

    
1269
            int numberLength = drawingNumber.Length;
1270
            while (drawingNameList.Contains(drawingNumber))
1271
            {
1272
                if (numberLength == drawingNumber.Length)
1273
                    drawingNumber += "-1";
1274
                else
1275
                {
1276
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1277
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1278
                    drawingNumber += ++index;
1279
                }
1280
            }
1281
            ReleaseCOMObjects(drawings);
1282
            drawings = null;
1283
        }
1284

    
1285
        /// <summary>
1286
        /// 도면 크기 구하는 메서드
1287
        /// </summary>
1288
        /// <returns></returns>
1289
        private bool DocumentCoordinateCorrection()
1290
        {
1291
            //if (radApp.ActiveDocument.ActiveSheet.SmartFrames2d.Count > 0)
1292
            //{
1293
            //    double x = 0;
1294
            //    double y = 0;
1295
            //    foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1296
            //    {
1297
            //        x = Math.Max(smartFrame.CropRight, x);
1298
            //        y = Math.Max(smartFrame.CropTop, y);
1299
            //    }
1300
            //    document.SetSPPIDLocation(x, y);
1301
            //    document.CoordinateCorrection();
1302
            //    return true;
1303
            //}
1304
            //else
1305
            //{
1306
            //    Log.Write("Need Border!");
1307
            //    return false;
1308
            //}
1309

    
1310
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1311
            {
1312
                Log.Write("Setting Drawing X, Drawing Y");
1313
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1314
                Log.Write("Start coordinate correction");
1315
                document.CoordinateCorrection();
1316
                return true;
1317
            }
1318
            else
1319
            {
1320
                Log.Write("Need Drawing X, Y");
1321
                return false;
1322
            }
1323
        }
1324

    
1325
        /// <summary>
1326
        /// 심볼을 실제로 Modeling 메서드
1327
        /// </summary>
1328
        /// <param name="symbol">생성할 심볼</param>
1329
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1330
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1331
        {
1332
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1333
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1334
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1335
                return;
1336
            // 이미 모델링 됐을 경우
1337
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1338
                return;
1339

    
1340
            LMSymbol _LMSymbol = null;
1341

    
1342
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1343
            double x = symbol.SPPID.ORIGINAL_X;
1344
            double y = symbol.SPPID.ORIGINAL_Y;
1345
            int mirror = 0;
1346
            double angle = symbol.ANGLE;
1347

    
1348
            // OPC 일경우 180도 일때 Mirror
1349
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1350
                mirror = 1;
1351

    
1352
            // Mirror 계산
1353
            if (symbol.FLIP == 1)
1354
            {
1355
                mirror = 1;
1356
                if (angle == Math.PI || angle == 0)
1357
                    angle += Math.PI;
1358
            }
1359

    
1360
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1361
            {
1362
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1363
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1364
                if (connector != null)
1365
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1366

    
1367
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1368
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1369
                if (temp != null)
1370
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1371
                ReleaseCOMObjects(temp);
1372
                temp = null;
1373

    
1374
                if (_LMSymbol != null && _TargetItem != null)
1375
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1376

    
1377
                ReleaseCOMObjects(_TargetItem);
1378
            }
1379
            else
1380
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1381

    
1382
            if (_LMSymbol != null)
1383
            {
1384
                _LMSymbol.Commit();
1385

    
1386
                // ConnCheck
1387
                List<string> ids = new List<string>();
1388
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1389
                {
1390
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1391
                        ids.Add(item.Id);
1392
                    ReleaseCOMObjects(item);
1393
                }
1394
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1395
                {
1396
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1397
                        ids.Add(item.Id);
1398
                    ReleaseCOMObjects(item);
1399
                }
1400

    
1401
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1402
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1403
                {
1404
                    double currentX = _LMSymbol.get_XCoordinate();
1405
                    double currentY = _LMSymbol.get_YCoordinate();
1406
                }
1407

    
1408
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1409
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1410
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1411

    
1412
                foreach (var item in symbol.ChildSymbols)
1413
                    CreateChildSymbol(item, _LMSymbol, symbol);
1414

    
1415
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1416
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1417

    
1418
                double[] range = null;
1419
                GetSPPIDSymbolRange(symbol, ref range);
1420
                symbol.SPPID.SPPID_Min_X = range[0];
1421
                symbol.SPPID.SPPID_Min_Y = range[1];
1422
                symbol.SPPID.SPPID_Max_X = range[2];
1423
                symbol.SPPID.SPPID_Max_Y = range[3];
1424

    
1425
                double xGap = symbol.SPPID.SPPID_X - symbol.SPPID.ORIGINAL_X;
1426
                double yGap = symbol.SPPID.SPPID_Y - symbol.SPPID.ORIGINAL_Y;
1427

    
1428
                List<Symbol> xGroupSymbols = symbol.SPPID.CorrectionX_GroupSymbols;
1429
                List<Symbol> yGroupSymbols = symbol.SPPID.CorrectionY_GroupSymbols;
1430
                xGroupSymbols.Sort(SPPIDUtil.SortSymbolPriority);
1431
                yGroupSymbols.Sort(SPPIDUtil.SortSymbolPriority);
1432
                int xDrawnCount = xGroupSymbols.Count(c => c.SPPID.RepresentationId != null);
1433
                int yDrawnCount = yGroupSymbols.Count(c => c.SPPID.RepresentationId != null);
1434

    
1435
                if (xDrawnCount == 1 || xDrawnCount == 2)
1436
                {
1437
                    for (int i = 0; i < xGroupSymbols.Count; i++)
1438
                    {
1439
                        var item = xGroupSymbols[i];
1440
                        if (!string.IsNullOrWhiteSpace(item.SPPID.RepresentationId)) continue;
1441

    
1442
                        if (xDrawnCount == 1)
1443
                        {                            
1444
                            item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1445
                            item.SPPID.ORIGINAL_Y = item.SPPID.ORIGINAL_Y + yGap;
1446
                        }
1447
                        else if (xDrawnCount == 2)
1448
                        {
1449
                            if (item.SPPID.IsEqualSpacingY)
1450
                            {
1451
                                double ppValue = xGroupSymbols[i - 2].SPPID.SPPID_Y != 0 ? xGroupSymbols[i - 2].SPPID.SPPID_Y : xGroupSymbols[i - 2].SPPID.ORIGINAL_Y;
1452
                                double pValue = xGroupSymbols[i - 1].SPPID.SPPID_Y != 0 ? xGroupSymbols[i - 1].SPPID.SPPID_Y : xGroupSymbols[i - 1].SPPID.ORIGINAL_Y;
1453
                                double gap = pValue - ppValue;
1454
                                double value = pValue + gap;
1455
                                item.SPPID.ORIGINAL_Y = value;
1456
                            }
1457
                        }
1458
                    }
1459
                }
1460

    
1461
                if (yDrawnCount == 1 || yDrawnCount == 2)
1462
                {
1463
                    for (int i = 0; i < yGroupSymbols.Count; i++)
1464
                    {
1465
                        var item = yGroupSymbols[i];
1466
                        if (!string.IsNullOrWhiteSpace(item.SPPID.RepresentationId)) continue;
1467

    
1468
                        if (yDrawnCount == 1)
1469
                        {
1470
                            item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1471
                            item.SPPID.ORIGINAL_X = item.SPPID.ORIGINAL_X + xGap;
1472
                        }
1473
                        else if (yDrawnCount == 2)
1474
                        {
1475
                            if (item.SPPID.IsEqualSpacingX)
1476
                            {
1477
                                double ppValue = yGroupSymbols[i - 2].SPPID.SPPID_X != 0 ? yGroupSymbols[i - 2].SPPID.SPPID_X : yGroupSymbols[i - 2].SPPID.ORIGINAL_X;
1478
                                double pValue = yGroupSymbols[i - 1].SPPID.SPPID_X != 0 ? yGroupSymbols[i - 1].SPPID.SPPID_X : yGroupSymbols[i - 1].SPPID.ORIGINAL_X;
1479
                                double gap = pValue - ppValue;
1480
                                double value = pValue + gap;
1481
                                item.SPPID.ORIGINAL_X = value;
1482
                            }
1483
                        }
1484
                    }
1485
                }
1486

    
1487
                ReleaseCOMObjects(_LMSymbol);
1488
            }
1489
        }
1490
        /// <summary>
1491
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1492
        /// Signal Point는 고려하지 않음
1493
        /// </summary>
1494
        /// <param name="symbol"></param>
1495
        /// <param name="_TargetItem"></param>
1496
        /// <param name="targetX"></param>
1497
        /// <param name="targetY"></param>
1498
        /// <returns></returns>
1499
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1500
        {
1501
            LMConnector tempConnector = null;
1502

    
1503
            List<Symbol> group = new List<Symbol>();
1504
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1505
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1506
            {
1507
                List<Connector> connectors = new List<Connector>();
1508
                foreach (var item in group)
1509
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1510
                /// Primary or Secondary Type Line만 고려
1511
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1512
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1513
                if (_connector != null)
1514
                {
1515
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1516
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1517
                    /// PipingPoint가 2개 이상만
1518
                    if (pointInfos.Count >= 2)
1519
                    {
1520
                        double lineX = 0;
1521
                        double lineY = 0;
1522
                        double length = 0;
1523
                        foreach (var item in pointInfos)
1524
                        {
1525
                            double tempX = item[1];
1526
                            double tempY = item[2];
1527

    
1528
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1529
                            if (calcDistance > length)
1530
                            {
1531
                                lineX = tempX;
1532
                                lineY = tempY;
1533
                            }
1534
                        }
1535

    
1536
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1537
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1538
                        placeRunInputs.AddPoint(-1, -1);
1539
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1540
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1541
                        if (tempConnector != null)
1542
                            tempConnector.Commit();
1543
                        ReleaseCOMObjects(_LMAItem);
1544
                        _LMAItem = null;
1545
                        ReleaseCOMObjects(placeRunInputs);
1546
                        placeRunInputs = null;
1547
                    }
1548
                }
1549
            }
1550

    
1551
            return tempConnector;
1552
        }
1553
        /// <summary>
1554
        /// Symbol의 PipingPoints를 구함
1555
        /// SignalPoint는 고려하지 않음
1556
        /// </summary>
1557
        /// <param name="symbol"></param>
1558
        /// <returns></returns>
1559
        private List<double[]> getPipingPoints(LMSymbol symbol)
1560
        {
1561
            LMModelItem modelItem = symbol.ModelItemObject;
1562
            LMPipingPoints pipingPoints = null;
1563
            if (modelItem.get_ItemTypeName() == "PipingComp")
1564
            {
1565
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1566
                pipingPoints = pipingComp.PipingPoints;
1567
                ReleaseCOMObjects(pipingComp);
1568
                pipingComp = null;
1569
            }
1570
            else if (modelItem.get_ItemTypeName() == "Instrument")
1571
            {
1572
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1573
                pipingPoints = instrument.PipingPoints;
1574
                ReleaseCOMObjects(instrument);
1575
                instrument = null;
1576
            }
1577
            else
1578
                Log.Write("다른 Type");
1579

    
1580
            List<double[]> info = new List<double[]>();
1581
            if (pipingPoints != null)
1582
            {
1583
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1584
                {
1585
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1586
                    {
1587
                        if (attribute.Name == "PipingPointNumber")
1588
                        {
1589
                            int index = Convert.ToInt32(attribute.get_Value());
1590
                            if (info.Find(loopX => loopX[0] == index) == null)
1591
                            {
1592
                                double x = 0;
1593
                                double y = 0;
1594
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1595
                                    info.Add(new double[] { index, x, y });
1596
                            }
1597
                        }
1598
                    }
1599
                }
1600
            }
1601
            ReleaseCOMObjects(modelItem);
1602
            modelItem = null;
1603
            ReleaseCOMObjects(pipingPoints);
1604
            pipingPoints = null;
1605

    
1606
            return info;
1607
        }
1608

    
1609
        private void RemoveSymbol(Symbol symbol)
1610
        {
1611
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1612
            {
1613
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1614
                if (_LMSymbol != null)
1615
                {
1616
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1617
                    ReleaseCOMObjects(_LMSymbol);
1618
                }
1619
            }
1620

    
1621
            symbol.SPPID.RepresentationId = string.Empty;
1622
            symbol.SPPID.ModelItemID = string.Empty;
1623
            symbol.SPPID.SPPID_X = double.NaN;
1624
            symbol.SPPID.SPPID_Y = double.NaN;
1625
            symbol.SPPID.SPPID_Min_X = double.NaN;
1626
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1627
            symbol.SPPID.SPPID_Max_X = double.NaN;
1628
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1629
        }
1630

    
1631
        private void RemoveSymbol(List<Symbol> symbols)
1632
        {
1633
            foreach (var symbol in symbols)
1634
            {
1635
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1636
                {
1637
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1638
                    if (_LMSymbol != null)
1639
                    {
1640
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1641
                        ReleaseCOMObjects(_LMSymbol);
1642
                    }
1643
                }
1644

    
1645
                symbol.SPPID.RepresentationId = string.Empty;
1646
                symbol.SPPID.ModelItemID = string.Empty;
1647
                symbol.SPPID.SPPID_X = double.NaN;
1648
                symbol.SPPID.SPPID_Y = double.NaN;
1649
                symbol.SPPID.SPPID_Min_X = double.NaN;
1650
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1651
                symbol.SPPID.SPPID_Max_X = double.NaN;
1652
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1653
            }
1654
        }
1655

    
1656
        /// <summary>
1657
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1658
        /// </summary>
1659
        /// <param name="targetConnector"></param>
1660
        /// <param name="targetSymbol"></param>
1661
        /// <param name="x"></param>
1662
        /// <param name="y"></param>
1663
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1664
        {
1665
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1666

    
1667
            double[] range = null;
1668
            List<double[]> points = new List<double[]>();
1669
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1670
            double x1 = range[0];
1671
            double y1 = range[1];
1672
            double x2 = range[2];
1673
            double y2 = range[3];
1674

    
1675
            // Origin 기준 Connector의 위치차이
1676
            double sceneX = 0;
1677
            double sceneY = 0;
1678
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1679
            double originX = 0;
1680
            double originY = 0;
1681
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1682
            double gapX = originX - sceneX;
1683
            double gapY = originY - sceneY;
1684

    
1685
            // SPPID Symbol과 ID2 심볼의 크기 차이
1686
            double sizeWidth = 0;
1687
            double sizeHeight = 0;
1688
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1689
            if (sizeWidth == 0 || sizeHeight == 0)
1690
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1691

    
1692
            double percentX = (x2 - x1) / sizeWidth;
1693
            double percentY = (y2 - y1) / sizeHeight;
1694

    
1695
            double SPPIDgapX = gapX * percentX;
1696
            double SPPIDgapY = gapY * percentY;
1697

    
1698
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1699
            double distance = double.MaxValue;
1700
            double[] resultPoint;
1701
            foreach (var point in points)
1702
            {
1703
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1704
                if (distance > result)
1705
                {
1706
                    distance = result;
1707
                    resultPoint = point;
1708
                    x = point[0];
1709
                    y = point[1];
1710
                }
1711
            }
1712

    
1713
            ReleaseCOMObjects(_TargetItem);
1714
        }
1715

    
1716
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1717
        {
1718
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1719
            if (index == 0)
1720
            {
1721
                x = targetLine.SPPID.START_X;
1722
                y = targetLine.SPPID.START_Y;
1723
            }
1724
            else
1725
            {
1726
                x = targetLine.SPPID.END_X;
1727
                y = targetLine.SPPID.END_Y;
1728
            }
1729
        }
1730

    
1731
        /// <summary>
1732
        /// SPPID Symbol의 Range를 구한다.
1733
        /// </summary>
1734
        /// <param name="symbol"></param>
1735
        /// <param name="range"></param>
1736
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1737
        {
1738
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1739
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1740
            double x1 = 0;
1741
            double y1 = 0;
1742
            double x2 = 0;
1743
            double y2 = 0;
1744
            symbol2d.Range(out x1, out y1, out x2, out y2);
1745
            range = new double[] { x1, y1, x2, y2 };
1746

    
1747
            for (int i = 1; i < 30; i++)
1748
            {
1749
                double connX = 0;
1750
                double connY = 0;
1751
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1752
                    points.Add(new double[] { connX, connY });
1753
            }
1754

    
1755
            foreach (var childSymbol in symbol.ChildSymbols)
1756
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1757

    
1758
            ReleaseCOMObjects(_TargetItem);
1759
        }
1760

    
1761
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1762
        {
1763
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1764
            if (_TargetItem != null)
1765
            {
1766
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1767
                double x1 = 0;
1768
                double y1 = 0;
1769
                double x2 = 0;
1770
                double y2 = 0;
1771
                if (!bForGraphic)
1772
                {
1773
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1774
                    range = new double[] { x1, y1, x2, y2 };
1775
                }
1776
                else
1777
                {
1778
                    x1 = double.MaxValue;
1779
                    y1 = double.MaxValue;
1780
                    x2 = double.MinValue;
1781
                    y2 = double.MinValue;
1782
                    range = new double[] { x1, y1, x2, y2 };
1783

    
1784
                    foreach (var item in symbol2d.DrawingObjects)
1785
                    {
1786
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1787
                        {
1788
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1789
                            if (rangeObject.Layer == "Default")
1790
                            {
1791
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1792
                                range = new double[] {
1793
                                Math.Min(x1, range[0]),
1794
                                Math.Min(y1, range[1]),
1795
                                Math.Max(x2, range[2]),
1796
                                Math.Max(y2, range[3])
1797
                            };
1798
                            }
1799
                        }
1800
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1801
                        {
1802
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1803
                            if (rangeObject.Layer == "Default")
1804
                            {
1805
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1806
                                range = new double[] {
1807
                                Math.Min(x1, range[0]),
1808
                                Math.Min(y1, range[1]),
1809
                                Math.Max(x2, range[2]),
1810
                                Math.Max(y2, range[3])
1811
                            };
1812
                            }
1813
                        }
1814
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1815
                        {
1816
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1817
                            if (rangeObject.Layer == "Default")
1818
                            {
1819
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1820
                                range = new double[] {
1821
                                Math.Min(x1, range[0]),
1822
                                Math.Min(y1, range[1]),
1823
                                Math.Max(x2, range[2]),
1824
                                Math.Max(y2, range[3])
1825
                            };
1826
                            }
1827
                        }
1828
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1829
                        {
1830
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1831
                            if (rangeObject.Layer == "Default")
1832
                            {
1833
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1834
                                range = new double[] {
1835
                                Math.Min(x1, range[0]),
1836
                                Math.Min(y1, range[1]),
1837
                                Math.Max(x2, range[2]),
1838
                                Math.Max(y2, range[3])
1839
                            };
1840
                            }
1841
                        }
1842
                    }
1843
                }
1844

    
1845
                if (!bOnlySymbol)
1846
                {
1847
                    foreach (var childSymbol in symbol.ChildSymbols)
1848
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1849
                }
1850
                ReleaseCOMObjects(_TargetItem);
1851
            }
1852
        }
1853

    
1854
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1855
        {
1856
            if (labelPersist != null)
1857
            {
1858
                double x1 = double.MaxValue;
1859
                double y1 = double.MaxValue;
1860
                double x2 = double.MinValue;
1861
                double y2 = double.MinValue;
1862
                range = new double[] { x1, y1, x2, y2 };
1863

    
1864
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1865
                foreach (var item in dependency.DrawingObjects)
1866
                {
1867
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1868
                    if (textBox != null)
1869
                    {
1870
                        if (dependency != null)
1871
                        {
1872
                            double tempX1;
1873
                            double tempY1;
1874
                            double tempX2;
1875
                            double tempY2;
1876
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1877
                            x1 = Math.Min(x1, tempX1);
1878
                            y1 = Math.Min(y1, tempY1);
1879
                            x2 = Math.Max(x2, tempX2);
1880
                            y2 = Math.Max(y2, tempY2);
1881

    
1882
                            range = new double[] { x1, y1, x2, y2 };
1883
                        }
1884
                    }
1885
                }
1886

    
1887
            }
1888
        }
1889

    
1890
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1891
        {
1892
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1893
            foreach (var symbol in symbols)
1894
            {
1895
                double[] symbolRange = null;
1896
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
1897

    
1898
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
1899
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
1900
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
1901
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
1902

    
1903
                foreach (var childSymbol in symbol.ChildSymbols)
1904
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1905
            }
1906

    
1907
            range = tempRange;
1908
        }
1909

    
1910
        /// <summary>
1911
        /// Child Modeling 된 Symbol의 Range를 구한다.
1912
        /// </summary>
1913
        /// <param name="childSymbol"></param>
1914
        /// <param name="range"></param>
1915
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1916
        {
1917
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1918
            if (_ChildSymbol != null)
1919
            {
1920
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1921
                double x1 = 0;
1922
                double y1 = 0;
1923
                double x2 = 0;
1924
                double y2 = 0;
1925
                symbol2d.Range(out x1, out y1, out x2, out y2);
1926
                range[0] = Math.Min(range[0], x1);
1927
                range[1] = Math.Min(range[1], y1);
1928
                range[2] = Math.Max(range[2], x2);
1929
                range[3] = Math.Max(range[3], y2);
1930

    
1931
                for (int i = 1; i < int.MaxValue; i++)
1932
                {
1933
                    double connX = 0;
1934
                    double connY = 0;
1935
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1936
                        points.Add(new double[] { connX, connY });
1937
                    else
1938
                        break;
1939
                }
1940

    
1941
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1942
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1943

    
1944
                ReleaseCOMObjects(_ChildSymbol);
1945
            }
1946
        }
1947

    
1948
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1949
        {
1950
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1951
            if (_ChildSymbol != null)
1952
            {
1953
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1954
                double x1 = 0;
1955
                double y1 = 0;
1956
                double x2 = 0;
1957
                double y2 = 0;
1958
                symbol2d.Range(out x1, out y1, out x2, out y2);
1959
                range[0] = Math.Min(range[0], x1);
1960
                range[1] = Math.Min(range[1], y1);
1961
                range[2] = Math.Max(range[2], x2);
1962
                range[3] = Math.Max(range[3], y2);
1963

    
1964
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1965
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1966
                ReleaseCOMObjects(_ChildSymbol);
1967
            }
1968
        }
1969

    
1970
        /// <summary>
1971
        /// Label Symbol Modeling
1972
        /// </summary>
1973
        /// <param name="symbol"></param>
1974
        private void LabelSymbolModeling(Symbol symbol)
1975
        {
1976
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1977
            {
1978
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1979
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1980
                    return;
1981
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1982

    
1983
                string symbolUID = itemAttribute.VALUE;
1984
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1985
                if (targetItem != null &&
1986
                    (targetItem.GetType() == typeof(Symbol) ||
1987
                    targetItem.GetType() == typeof(Equipment)))
1988
                {
1989
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1990
                    string sRep = null;
1991
                    if (targetItem.GetType() == typeof(Symbol))
1992
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1993
                    else if (targetItem.GetType() == typeof(Equipment))
1994
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1995
                    if (!string.IsNullOrEmpty(sRep))
1996
                    {
1997
                        // LEADER Line 검사
1998
                        bool leaderLine = false;
1999
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
2000
                        if (symbolMapping != null)
2001
                            leaderLine = symbolMapping.LEADERLINE;
2002

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

    
2007
                        //Leader 선 센터로
2008
                        if (_LMLabelPresist != null)
2009
                        {
2010
                            // Target Item에 Label의 Attribute Input
2011
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
2012

    
2013
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
2014
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
2015
                            if (dependency != null)
2016
                            {
2017
                                bool result = false;
2018
                                foreach (var attributes in dependency.AttributeSets)
2019
                                {
2020
                                    foreach (var attribute in attributes)
2021
                                    {
2022
                                        string name = attribute.Name;
2023
                                        string value = attribute.GetValue().ToString();
2024
                                        if (name == "DrawingItemType" && value == "LabelPersist")
2025
                                        {
2026
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
2027
                                            {
2028
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
2029
                                                {
2030
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
2031
                                                    double prevX = _TargetItem.get_XCoordinate();
2032
                                                    double prevY = _TargetItem.get_YCoordinate();
2033
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
2034
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
2035
                                                    result = true;
2036
                                                    break;
2037
                                                }
2038
                                            }
2039
                                        }
2040

    
2041
                                        if (result)
2042
                                            break;
2043
                                    }
2044

    
2045
                                    if (result)
2046
                                        break;
2047
                                }
2048
                            }
2049

    
2050
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
2051
                            _LMLabelPresist.Commit();
2052
                            ReleaseCOMObjects(_LMLabelPresist);
2053
                        }
2054

    
2055
                        ReleaseCOMObjects(_TargetItem);
2056
                    }
2057
                }
2058
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
2059
                {
2060
                    Line targetLine = targetItem as Line;
2061
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
2062
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
2063
                    if (connectedLMConnector != null)
2064
                    {
2065
                        // Target Item에 Label의 Attribute Input
2066
                        InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
2067

    
2068
                        // LEADER Line 검사
2069
                        bool leaderLine = false;
2070
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
2071
                        if (symbolMapping != null)
2072
                            leaderLine = symbolMapping.LEADERLINE;
2073

    
2074
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: symbol.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
2075
                        if (_LMLabelPresist != null)
2076
                        {
2077
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
2078
                            _LMLabelPresist.Commit();
2079
                            ReleaseCOMObjects(_LMLabelPresist);
2080
                        }
2081
                        ReleaseCOMObjects(connectedLMConnector);
2082
                    }
2083

    
2084
                    foreach (var item in connectorVertices)
2085
                        if (item.Key != null)
2086
                            ReleaseCOMObjects(item.Key);
2087
                }
2088
            }
2089
        }
2090

    
2091
        /// <summary>
2092
        /// Equipment를 실제로 Modeling 메서드
2093
        /// </summary>
2094
        /// <param name="equipment"></param>
2095
        private void EquipmentModeling(Equipment equipment)
2096
        {
2097
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
2098
                return;
2099

    
2100
            LMSymbol _LMSymbol = null;
2101
            LMSymbol targetItem = null;
2102
            string mappingPath = equipment.SPPID.MAPPINGNAME;
2103
            double x = equipment.SPPID.ORIGINAL_X;
2104
            double y = equipment.SPPID.ORIGINAL_Y;
2105
            int mirror = 0;
2106
            double angle = equipment.ANGLE;
2107

    
2108
            // Mirror 계산
2109
            if (equipment.FLIP == 1)
2110
            {
2111
                mirror = 1;
2112
                if (angle == Math.PI || angle == 0)
2113
                    angle += Math.PI;
2114
            }
2115

    
2116
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
2117

    
2118
            Connector connector = equipment.CONNECTORS.Find(conn =>
2119
            !string.IsNullOrEmpty(conn.CONNECTEDITEM) &&
2120
            conn.CONNECTEDITEM != "None" &&
2121
            conn.ConnectedObject.GetType() == typeof(Equipment));
2122

    
2123
            if (connector != null)
2124
            {
2125
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
2126
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
2127
                if (connEquipment != null)
2128
                {
2129
                    //if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2130
                    //    EquipmentModeling(connEquipment);
2131

    
2132
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
2133
                    {
2134
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
2135
                        if (targetItem != null)
2136
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2137
                        else
2138
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2139
                    }
2140
                    else
2141
                    {
2142
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2143
                    }
2144
                }
2145
                else if (connVendorPackage != null)
2146
                {
2147
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
2148
                    {
2149
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
2150
                        if (targetItem != null)
2151
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
2152
                        else
2153
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2154
                    }
2155
                }
2156
                else
2157
                {
2158
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2159
                }
2160
            }
2161
            else
2162
            {
2163
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
2164
            }
2165

    
2166
            if (_LMSymbol != null)
2167
            {
2168
                _LMSymbol.Commit();
2169
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2170
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
2171
                ReleaseCOMObjects(_LMSymbol);
2172
            }
2173

    
2174
            if (targetItem != null)
2175
            {
2176
                ReleaseCOMObjects(targetItem);
2177
            }
2178

    
2179
            ReleaseCOMObjects(_LMSymbol);
2180
        }
2181

    
2182
        private void VendorPackageModeling(VendorPackage vendorPackage)
2183
        {
2184
            ETCSetting setting = ETCSetting.GetInstance();
2185
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2186
            {
2187
                string symbolPath = setting.VendorPackageSymbolPath;
2188
                double x = vendorPackage.SPPID.ORIGINAL_X;
2189
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2190

    
2191
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2192
                if (symbol != null)
2193
                {
2194
                    symbol.Commit();
2195
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2196
                }
2197

    
2198
                ReleaseCOMObjects(symbol);
2199
                symbol = null;
2200
            }
2201
        }
2202

    
2203
        private void GraphicModeling(Graphic graphic)
2204
        {
2205
            Ingr.RAD2D.SmartFrame2d borderFrame = radApp.ActiveDocument.ActiveSheet.SmartFrames2d[0];
2206
            string styleName = "SFStyleConverter";
2207
            string projectPah = Settings.Default.ProjectPath;
2208
            string graphicDirectory = Path.Combine(projectPah, "graphic");
2209
            string filePath = Path.Combine(graphicDirectory, string.Format("{0}.igr", graphic.NAME));
2210
            if (!File.Exists(filePath)) return;
2211

    
2212
            int styleCount = radApp.ActiveDocument.SmartFrame2dStyles.Count(c => c.Name.StartsWith(styleName));
2213
            styleName = string.Format("{0}_{1}", styleName, styleCount);
2214
            Ingr.RAD2D.SmartFrame2dStyle StyleConverter = radApp.ActiveDocument.SmartFrame2dStyles.Add(styleName, "");
2215

    
2216
            Ingr.RAD2D.SmartFrame2d smartFrame = radApp.ActiveDocument.ActiveSheet.SmartFrames2d.AddBy2Points(styleName, 0.01, 0.01, 0.1, 0.1, false, filePath);
2217
            smartFrame.BorderVisible = false;
2218
            smartFrame.SetLayerDisplay("default", true);
2219

    
2220
            double oMinx = 0, oMinY = 0, oMaxX = 0, oMaxY = 0;
2221
            smartFrame.Range(out oMinx, out oMinY, out oMaxX, out oMaxY);
2222
            double cWidth = oMaxX - oMinx;
2223
            double cHeight = oMaxY - oMinY;
2224
            double height = Math.Abs(graphic.SPPIDGraphicLocation.Y2 - graphic.SPPIDGraphicLocation.Y1);
2225
            double width = Math.Abs(graphic.SPPIDGraphicLocation.X2 - graphic.SPPIDGraphicLocation.X1);
2226
            double scaleFactor = width / cWidth;
2227
            smartFrame.ScaleFactor = scaleFactor;
2228
            smartFrame.SetOrigin(graphic.SPPIDGraphicLocation.X1, graphic.SPPIDGraphicLocation.Y1);
2229
        }
2230

    
2231
        /// <summary>
2232
        /// 첫 진입점
2233
        /// </summary>
2234
        /// <param name="symbol"></param>
2235
        private void SymbolModelingBySymbol(Symbol symbol)
2236
        {
2237
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2238
            List<object> endObjects = new List<object>();
2239
            endObjects.Add(symbol);
2240

    
2241
            // 심볼에 연결되어 있는 항목들을 모델링한다
2242
            foreach (var connector in symbol.CONNECTORS)
2243
            {
2244
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2245
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2246
                {
2247
                    endObjects.Add(connItem);
2248
                    if (connItem.GetType() == typeof(Symbol))
2249
                    {
2250
                        Symbol connSymbol = connItem as Symbol;
2251
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2252
                        {
2253
                            SymbolModeling(connSymbol, symbol);
2254
                        }
2255
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2256
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2257
                    }
2258
                    else if (connItem.GetType() == typeof(Line))
2259
                    {
2260
                        Line connLine = connItem as Line;
2261
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2262
                    }
2263
                }
2264
            }
2265
        }
2266

    
2267
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2268
        {
2269
            foreach (var connector in symbol.CONNECTORS)
2270
            {
2271
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2272
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2273
                {
2274
                    if (!endObjects.Contains(connItem))
2275
                    {
2276
                        endObjects.Add(connItem);
2277
                        if (connItem.GetType() == typeof(Symbol))
2278
                        {
2279
                            Symbol connSymbol = connItem as Symbol;
2280
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2281
                            {
2282
                                SymbolModeling(connSymbol, symbol);
2283
                            }
2284
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2285
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2286
                        }
2287
                        else if (connItem.GetType() == typeof(Line))
2288
                        {
2289
                            Line connLine = connItem as Line;
2290
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2291
                        }
2292
                    }
2293
                }
2294
            }
2295
        }
2296

    
2297
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2298
        {
2299
            foreach (var connector in line.CONNECTORS)
2300
            {
2301
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2302
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2303
                {
2304
                    if (!endObjects.Contains(connItem))
2305
                    {
2306
                        endObjects.Add(connItem);
2307
                        if (connItem.GetType() == typeof(Symbol))
2308
                        {
2309
                            Symbol connSymbol = connItem as Symbol;
2310
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2311
                            {
2312
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2313
                                int branchCount = 0;
2314
                                if (connLine != null)
2315
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2316

    
2317
                                List<Symbol> group = new List<Symbol>();
2318
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2319
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2320
                                List<Symbol> endModelingGroup = new List<Symbol>();
2321
                                if (priority != null)
2322
                                {
2323
                                    SymbolGroupModeling(priority, group);
2324

    
2325
                                    // Range 겹치는지 확인해야함
2326
                                    double[] prevRange = null;
2327
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2328
                                    double[] groupRange = null;
2329
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
2330

    
2331
                                    double distanceX = 0;
2332
                                    double distanceY = 0;
2333
                                    bool overlapX = false;
2334
                                    bool overlapY = false;
2335
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2336
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2337
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2338
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2339
                                    {
2340
                                        RemoveSymbol(group);
2341
                                        foreach (var _temp in group)
2342
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2343

    
2344
                                        SymbolGroupModeling(priority, group);
2345
                                    }
2346
                                    else if (branchCount > 0)
2347
                                    {
2348
                                        LMConnector _connector = JustLineModeling(connLine);
2349
                                        if (_connector != null)
2350
                                        {
2351
                                            double distance = GetConnectorDistance(_connector);
2352
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2353
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2354
                                            _connector.Commit();
2355
                                            ReleaseCOMObjects(_connector);
2356
                                            _connector = null;
2357
                                            if (cellCount < branchCount + 1)
2358
                                            {
2359
                                                int moveCount = branchCount - cellCount;
2360
                                                RemoveSymbol(group);
2361
                                                foreach (var _temp in group)
2362
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2363

    
2364
                                                SymbolGroupModeling(priority, group);
2365
                                            }
2366
                                        }
2367
                                    }
2368
                                }
2369
                                else
2370
                                {
2371
                                    SymbolModeling(connSymbol, null);
2372
                                    // Range 겹치는지 확인해야함
2373
                                    double[] prevRange = null;
2374
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange, bForGraphic: true);
2375
                                    double[] connRange = null;
2376
                                    GetSPPIDSymbolRange(connSymbol, ref connRange, bForGraphic: true);
2377

    
2378
                                    double distanceX = 0;
2379
                                    double distanceY = 0;
2380
                                    bool overlapX = false;
2381
                                    bool overlapY = false;
2382
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2383
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2384
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2385
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2386
                                    {
2387
                                        RemoveSymbol(connSymbol);
2388
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2389

    
2390
                                        SymbolModeling(connSymbol, null);
2391
                                    }
2392
                                    else if (branchCount > 0)
2393
                                    {
2394
                                        LMConnector _connector = JustLineModeling(connLine);
2395
                                        if (_connector != null)
2396
                                        {
2397
                                            double distance = GetConnectorDistance(_connector);
2398
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2399
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2400
                                            _connector.Commit();
2401
                                            ReleaseCOMObjects(_connector);
2402
                                            _connector = null;
2403
                                            if (cellCount < branchCount + 1)
2404
                                            {
2405
                                                int moveCount = branchCount - cellCount;
2406
                                                RemoveSymbol(group);
2407
                                                foreach (var _temp in group)
2408
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2409

    
2410
                                                SymbolGroupModeling(priority, group);
2411
                                            }
2412
                                        }
2413
                                    }
2414
                                }
2415
                            }
2416
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2417
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2418
                        }
2419
                        else if (connItem.GetType() == typeof(Line))
2420
                        {
2421
                            Line connLine = connItem as Line;
2422
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2423
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2424
                        }
2425
                    }
2426
                }
2427
            }
2428
        }
2429

    
2430
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2431
        {
2432
            List<Symbol> endModelingGroup = new List<Symbol>();
2433
            SymbolModeling(firstSymbol, null);
2434
            endModelingGroup.Add(firstSymbol);
2435
            while (endModelingGroup.Count != group.Count)
2436
            {
2437
                foreach (var _symbol in group)
2438
                {
2439
                    if (!endModelingGroup.Contains(_symbol))
2440
                    {
2441
                        foreach (var _connector in _symbol.CONNECTORS)
2442
                        {
2443
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2444
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2445
                            {
2446
                                SymbolModeling(_symbol, _connSymbol);
2447
                                endModelingGroup.Add(_symbol);
2448
                                break;
2449
                            }
2450
                        }
2451
                    }
2452
                }
2453
            }
2454
        }
2455

    
2456
        /// <summary>
2457
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2458
        /// </summary>
2459
        /// <param name="childSymbol"></param>
2460
        /// <param name="parentSymbol"></param>
2461
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2462
        {
2463
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2464
            double x1 = 0;
2465
            double x2 = 0;
2466
            double y1 = 0;
2467
            double y2 = 0;
2468
            symbol2d.Range(out x1, out y1, out x2, out y2);
2469

    
2470
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2471
            if (_LMSymbol != null)
2472
            {
2473
                _LMSymbol.Commit();
2474
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2475
                foreach (var item in childSymbol.ChildSymbols)
2476
                    CreateChildSymbol(item, _LMSymbol, parent);
2477
            }
2478

    
2479

    
2480
            ReleaseCOMObjects(_LMSymbol);
2481
        }
2482
        double index = 0;
2483
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2484
        {
2485
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2486
                return;
2487

    
2488
            List<Line> group = new List<Line>();
2489
            GetConnectedLineGroup(line, group);
2490
            LineCoordinateCorrection(group);
2491

    
2492
            foreach (var groupLine in group)
2493
            {
2494
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2495
                {
2496
                    BranchLines.Add(groupLine);
2497
                    continue;
2498
                }
2499

    
2500
                bool diagonal = false;
2501
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2502
                    diagonal = true;
2503
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2504
                LMSymbol _LMSymbolStart = null;
2505
                LMSymbol _LMSymbolEnd = null;
2506
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2507
                foreach (var connector in groupLine.CONNECTORS)
2508
                {
2509
                    double x = 0;
2510
                    double y = 0;
2511
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2512
                    if (connector.ConnectedObject == null)
2513
                        placeRunInputs.AddPoint(x, y);
2514
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2515
                    {
2516
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2517
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2518
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2519
                        {
2520
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2521
                            if (_LMSymbolStart != null)
2522
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2523
                            else
2524
                                placeRunInputs.AddPoint(x, y);
2525
                        }
2526
                        else
2527
                        {
2528
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2529
                            if (_LMSymbolEnd != null)
2530
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2531
                            else
2532
                                placeRunInputs.AddPoint(x, y);
2533
                        }
2534
                    }
2535
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2536
                    {
2537
                        Line targetLine = connector.ConnectedObject as Line;
2538
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2539
                        {
2540
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2541
                            if (targetConnector != null)
2542
                            {
2543
                                if (targetLine.SlopeType != SlopeType.HORIZONTAL && targetLine.SlopeType != SlopeType.VERTICAL)
2544
                                    diagonal = true;
2545
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2546
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2547
                            }
2548
                            else
2549
                            {
2550
                                placeRunInputs.AddPoint(x, y);
2551
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2552
                            }
2553
                        }
2554
                        else
2555
                        {
2556
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2557
                            {
2558
                                index += 0.01;
2559
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2560
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2561
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2562
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2563
                                else
2564
                                {
2565
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2566
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2567
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2568
                                    else
2569
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2570
                                }
2571
                            }
2572

    
2573
                            placeRunInputs.AddPoint(x, y);
2574

    
2575
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2576
                            {
2577
                                index += 0.01;
2578
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2579
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2580
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2581
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2582
                                else
2583
                                {
2584
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2585
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2586
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2587
                                    else
2588
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2589
                                }
2590
                            }
2591
                        }
2592
                    }
2593
                    else
2594
                        placeRunInputs.AddPoint(x, y);
2595
                }
2596

    
2597
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2598
                if (_lMConnector != null)
2599
                {
2600
                    _lMConnector.Commit();
2601
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2602

    
2603
                    bool bRemodelingStart = false;
2604
                    if (_LMSymbolStart != null)
2605
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2606
                    bool bRemodelingEnd = false;
2607
                    if (_LMSymbolEnd != null)
2608
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2609

    
2610
                    if (bRemodelingStart || bRemodelingEnd)
2611
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2612

    
2613
                    FlowMarkModeling(groupLine);
2614

    
2615
                    ReleaseCOMObjects(_lMConnector);
2616

    
2617
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2618
                    if (modelItem != null)
2619
                    {
2620
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2621
                        if (attribute != null)
2622
                            attribute.set_Value("End 1 is upstream (Inlet)");
2623
                        modelItem.Commit();
2624
                    }
2625
                    ReleaseCOMObjects(modelItem);
2626
                    modelItem = null;
2627
                }
2628
                else if (!isBranchModeling)
2629
                {
2630
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2631
                }
2632

    
2633
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2634
                x.ConnectedObject != null &&
2635
                x.ConnectedObject.GetType() == typeof(Line) &&
2636
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2637
                .Select(x => x.ConnectedObject)
2638
                .ToList();
2639

    
2640
                foreach (var item in removeLines)
2641
                    RemoveLineForModeling(item as Line);
2642

    
2643
                ReleaseCOMObjects(_LMAItem);
2644
                _LMAItem = null;
2645
                ReleaseCOMObjects(placeRunInputs);
2646
                placeRunInputs = null;
2647
                ReleaseCOMObjects(_LMSymbolStart);
2648
                _LMSymbolStart = null;
2649
                ReleaseCOMObjects(_LMSymbolEnd);
2650
                _LMSymbolEnd = null;
2651

    
2652
                if (isBranchModeling && BranchLines.Contains(groupLine))
2653
                    BranchLines.Remove(groupLine);
2654
            }
2655
        }
2656

    
2657
        private LMConnector JustLineModeling(Line line)
2658
        {
2659
            bool diagonal = false;
2660
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2661
                diagonal = true;
2662
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2663
            LMSymbol _LMSymbolStart = null;
2664
            LMSymbol _LMSymbolEnd = null;
2665
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2666
            foreach (var connector in line.CONNECTORS)
2667
            {
2668
                double x = 0;
2669
                double y = 0;
2670
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2671
                if (connector.ConnectedObject == null)
2672
                {
2673
                    placeRunInputs.AddPoint(x, y);
2674
                }
2675
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2676
                {
2677
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2678
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2679
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2680
                    {
2681
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2682
                        if (_LMSymbolStart != null)
2683
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2684
                        else
2685
                            placeRunInputs.AddPoint(x, y);
2686
                    }
2687
                    else
2688
                    {
2689
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2690
                        if (_LMSymbolEnd != null)
2691
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2692
                        else
2693
                            placeRunInputs.AddPoint(x, y);
2694
                    }
2695
                }
2696
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2697
                {
2698
                    Line targetLine = connector.ConnectedObject as Line;
2699
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2700
                    {
2701
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2702
                        if (targetConnector != null)
2703
                        {
2704
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2705
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2706
                        }
2707
                        else
2708
                        {
2709
                            placeRunInputs.AddPoint(x, y);
2710
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2711
                        }
2712
                    }
2713
                    else
2714
                        placeRunInputs.AddPoint(x, y);
2715
                }
2716
            }
2717

    
2718
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2719
            if (_lMConnector != null)
2720
                _lMConnector.Commit();
2721

    
2722
            ReleaseCOMObjects(_LMAItem);
2723
            _LMAItem = null;
2724
            ReleaseCOMObjects(placeRunInputs);
2725
            placeRunInputs = null;
2726
            ReleaseCOMObjects(_LMSymbolStart);
2727
            _LMSymbolStart = null;
2728
            ReleaseCOMObjects(_LMSymbolEnd);
2729
            _LMSymbolEnd = null;
2730

    
2731
            return _lMConnector;
2732
        }
2733

    
2734
        private void RemoveLineForModeling(Line line)
2735
        {
2736
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2737
            if (modelItem != null)
2738
            {
2739
                foreach (LMRepresentation rep in modelItem.Representations)
2740
                {
2741
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2742
                    {
2743
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2744
                        dynamic OID = rep.get_GraphicOID().ToString();
2745
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2746
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2747
                        int verticesCount = lineStringGeometry.VertexCount;
2748
                        double[] vertices = null;
2749
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2750
                        for (int i = 0; i < verticesCount; i++)
2751
                        {
2752
                            double x = 0;
2753
                            double y = 0;
2754
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2755
                            if (verticesCount == 2 && (x < 0 || y < 0))
2756
                                _placement.PIDRemovePlacement(rep);
2757
                        }
2758
                        ReleaseCOMObjects(_LMConnector);
2759
                    }
2760
                }
2761

    
2762
                ReleaseCOMObjects(modelItem);
2763
            }
2764
        }
2765

    
2766
        private void RemoveLine(Line line)
2767
        {
2768
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2769
            if (modelItem != null)
2770
            {
2771
                foreach (LMRepresentation rep in modelItem.Representations)
2772
                {
2773
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2774
                        _placement.PIDRemovePlacement(rep);
2775
                }
2776
                ReleaseCOMObjects(modelItem);
2777
            }
2778
            line.SPPID.ModelItemId = null;
2779
        }
2780

    
2781
        private void GetConnectedLineGroup(Line line, List<Line> group)
2782
        {
2783
            if (!group.Contains(line))
2784
                group.Add(line);
2785
            foreach (var connector in line.CONNECTORS)
2786
            {
2787
                if (connector.ConnectedObject != null &&
2788
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2789
                    !group.Contains(connector.ConnectedObject) &&
2790
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2791
                {
2792
                    Line connLine = connector.ConnectedObject as Line;
2793
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2794
                    {
2795
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2796
                            group.Insert(0, connLine);
2797
                        else
2798
                            group.Add(connLine);
2799
                        GetConnectedLineGroup(connLine, group);
2800
                    }
2801
                }
2802
            }
2803
        }
2804

    
2805
        private void LineCoordinateCorrection(List<Line> group)
2806
        {
2807
            // 순서대로 전 Item 기준 정렬
2808
            LineCoordinateCorrectionByStart(group);
2809

    
2810
            // 역으로 심볼이 있을 경우 좌표 보정
2811
            LineCoordinateCorrectionForLastLine(group);
2812
        }
2813

    
2814
        private void LineCoordinateCorrectionByStart(List<Line> group)
2815
        {
2816
            for (int i = 0; i < group.Count; i++)
2817
            {
2818
                Line line = group[i];
2819
                if (i == 0)
2820
                {
2821
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2822
                    if (symbolConnector != null)
2823
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2824
                }
2825
                else if (i != 0)
2826
                {
2827
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2828
                }
2829
            }
2830
        }
2831

    
2832
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2833
        {
2834
            Line checkLine = group[group.Count - 1];
2835
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2836
            if (lastSymbolConnector != null)
2837
            {
2838
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2839
                for (int i = group.Count - 2; i >= 0; i--)
2840
                {
2841
                    Line line = group[i + 1];
2842
                    Line prevLine = group[i];
2843

    
2844
                    // 같으면 보정
2845
                    if (line.SlopeType == prevLine.SlopeType)
2846
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2847
                    else
2848
                    {
2849
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2850
                        {
2851
                            double prevX = 0;
2852
                            double prevY = 0;
2853
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2854
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2855

    
2856
                            double x = 0;
2857
                            double y = 0;
2858
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2859
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2860
                        }
2861
                        else if (line.SlopeType == SlopeType.VERTICAL)
2862
                        {
2863
                            double prevX = 0;
2864
                            double prevY = 0;
2865
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2866
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2867

    
2868
                            double x = 0;
2869
                            double y = 0;
2870
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2871
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2872
                        }
2873
                        break;
2874
                    }
2875
                }
2876
            }
2877
        }
2878

    
2879
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2880
        {
2881
            double x = 0;
2882
            double y = 0;
2883
            if (connItem.GetType() == typeof(Symbol))
2884
            {
2885
                Symbol targetSymbol = connItem as Symbol;
2886
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2887
                if (targetConnector != null)
2888
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2889
                else
2890
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2891
            }
2892
            else if (connItem.GetType() == typeof(Line))
2893
            {
2894
                Line targetLine = connItem as Line;
2895
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2896
            }
2897

    
2898
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2899
        }
2900

    
2901
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2902
        {
2903
            bool isReverseX = line.SPPID.END_X - line.SPPID.START_X < 0;
2904
            bool isReverseY = line.SPPID.END_Y - line.SPPID.START_Y < 0;
2905

    
2906
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2907
            int index = line.CONNECTORS.IndexOf(connector);
2908
            if (index == 0)
2909
            {                
2910
                line.SPPID.START_X = x;
2911
                line.SPPID.START_Y = y;
2912
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2913
                {
2914
                    line.SPPID.END_Y = y;
2915
                    // START_X가 END_X 값을 벗어날 경우 END_X 값 보정
2916
                    if ((line.SPPID.END_X - line.SPPID.START_X) * (!isReverseX ? 1 : -1) <= 0)
2917
                    {
2918
                        line.SPPID.END_X = line.SPPID.START_X + (GridSetting.GetInstance().Length * (!isReverseX ? 1 : -1));
2919
                    }
2920
                }
2921
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2922
                {
2923
                    line.SPPID.END_X = x;
2924
                    // START_Y가 END_Y 값을 벗어날 경우 END_Y 값 보정
2925
                    if ((line.SPPID.END_Y - line.SPPID.START_Y) * (!isReverseY ? 1 : -1) <= 0)
2926
                    {
2927
                        line.SPPID.END_Y = line.SPPID.START_Y + (GridSetting.GetInstance().Length * (!isReverseY ? 1 : -1));
2928
                    }
2929
                }
2930
            }
2931
            else
2932
            {
2933
                line.SPPID.END_X = x;
2934
                line.SPPID.END_Y = y;
2935
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2936
                {
2937
                    line.SPPID.START_Y = y;
2938
                    // END_X가 START_X 값을 벗어날 경우 START_X 값 보정
2939
                    if ((line.SPPID.END_X - line.SPPID.START_X) * (isReverseX ? 1 : -1) <= 0)
2940
                    {
2941
                        line.SPPID.START_X = line.SPPID.END_X - (GridSetting.GetInstance().Length * (!isReverseX ? 1 : -1));
2942
                    }
2943
                }
2944
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2945
                {
2946
                    line.SPPID.START_X = x;
2947
                    // END_Y가 START_Y 값을 벗어날 경우 START_Y 값 보정
2948
                    if ((line.SPPID.END_Y - line.SPPID.START_Y) * (isReverseY ? 1 : -1) <= 0)
2949
                    {
2950
                        line.SPPID.START_Y = line.SPPID.END_Y - (GridSetting.GetInstance().Length * (!isReverseY ? 1 : -1));
2951
                    }
2952
                }
2953
            }
2954
        }
2955

    
2956
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2957
        {
2958
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2959
            int index = line.CONNECTORS.IndexOf(connector);
2960
            if (index == 0)
2961
            {
2962
                line.SPPID.START_X = x;
2963
                if (line.SlopeType == SlopeType.VERTICAL)
2964
                    line.SPPID.END_X = x;
2965
            }
2966
            else
2967
            {
2968
                line.SPPID.END_X = x;
2969
                if (line.SlopeType == SlopeType.VERTICAL)
2970
                    line.SPPID.START_X = x;
2971
            }
2972
        }
2973

    
2974
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2975
        {
2976
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2977
            int index = line.CONNECTORS.IndexOf(connector);
2978
            if (index == 0)
2979
            {
2980
                line.SPPID.START_Y = y;
2981
                if (line.SlopeType == SlopeType.HORIZONTAL)
2982
                    line.SPPID.END_Y = y;
2983
            }
2984
            else
2985
            {
2986
                line.SPPID.END_Y = y;
2987
                if (line.SlopeType == SlopeType.HORIZONTAL)
2988
                    line.SPPID.START_Y = y;
2989
            }
2990
        }
2991

    
2992
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2993
        {
2994
            if (symbol != null)
2995
            {
2996
                string repID = symbol.AsLMRepresentation().Id;
2997
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2998
                string lineUID = line.UID;
2999

    
3000
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
3001
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
3002
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
3003

    
3004
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
3005
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
3006
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
3007

    
3008
                if (startSpecBreak != null || startEndBreak != null)
3009
                    result = true;
3010
            }
3011
        }
3012

    
3013
        /// <summary>
3014
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
3015
        /// </summary>
3016
        /// <param name="lines"></param>
3017
        /// <param name="prevLMConnector"></param>
3018
        /// <param name="startSymbol"></param>
3019
        /// <param name="endSymbol"></param>
3020
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
3021
        {
3022
            string symbolPath = string.Empty;
3023
            #region get symbol path
3024
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
3025
            symbolPath = GetSPPIDFileName(modelItem);
3026
            ReleaseCOMObjects(modelItem);
3027
            #endregion
3028
            bool diagonal = false;
3029
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
3030
                diagonal = true;
3031
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3032
            LMConnector newConnector = null;
3033
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
3034
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3035
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3036
            int verticesCount = lineStringGeometry.VertexCount;
3037
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3038

    
3039
            List<double[]> vertices = new List<double[]>();
3040
            for (int i = 1; i <= verticesCount; i++)
3041
            {
3042
                double x = 0;
3043
                double y = 0;
3044
                lineStringGeometry.GetVertex(i, ref x, ref y);
3045
                vertices.Add(new double[] { x, y });
3046
            }
3047

    
3048
            for (int i = 0; i < vertices.Count; i++)
3049
            {
3050
                double[] points = vertices[i];
3051
                // 시작 심볼이 있고 첫번째 좌표일 때
3052
                if (startSymbol != null && i == 0)
3053
                {
3054
                    if (bStart)
3055
                    {
3056
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
3057
                        if (slopeType == SlopeType.HORIZONTAL)
3058
                            placeRunInputs.AddPoint(points[0], -0.1);
3059
                        else if (slopeType == SlopeType.VERTICAL)
3060
                            placeRunInputs.AddPoint(-0.1, points[1]);
3061
                        else
3062
                            placeRunInputs.AddPoint(points[0], -0.1);
3063

    
3064
                        placeRunInputs.AddPoint(points[0], points[1]);
3065
                    }
3066
                    else
3067
                    {
3068
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
3069
                    }
3070
                }
3071
                // 마지막 심볼이 있고 마지막 좌표일 때
3072
                else if (endSymbol != null && i == vertices.Count - 1)
3073
                {
3074
                    if (bEnd)
3075
                    {
3076
                        placeRunInputs.AddPoint(points[0], points[1]);
3077

    
3078
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
3079
                        if (slopeType == SlopeType.HORIZONTAL)
3080
                            placeRunInputs.AddPoint(points[0], -0.1);
3081
                        else if (slopeType == SlopeType.VERTICAL)
3082
                            placeRunInputs.AddPoint(-0.1, points[1]);
3083
                        else
3084
                            placeRunInputs.AddPoint(points[0], -0.1);
3085
                    }
3086
                    else
3087
                    {
3088
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
3089
                    }
3090
                }
3091
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
3092
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
3093
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
3094
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
3095
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
3096
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
3097
                else
3098
                    placeRunInputs.AddPoint(points[0], points[1]);
3099
            }
3100

    
3101
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
3102
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3103

    
3104
            ReleaseCOMObjects(placeRunInputs);
3105
            ReleaseCOMObjects(_LMAItem);
3106
            ReleaseCOMObjects(modelItem);
3107

    
3108
            if (newConnector != null)
3109
            {
3110
                newConnector.Commit();
3111
                if (startSymbol != null && bStart)
3112
                {
3113
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
3114
                    placeRunInputs = new PlaceRunInputs();
3115
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
3116
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
3117
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3118
                    if (_LMConnector != null)
3119
                    {
3120
                        _LMConnector.Commit();
3121
                        RemoveConnectorForReModelingLine(newConnector);
3122
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
3123
                        ReleaseCOMObjects(_LMConnector);
3124
                    }
3125
                    ReleaseCOMObjects(placeRunInputs);
3126
                    ReleaseCOMObjects(_LMAItem);
3127
                }
3128

    
3129
                if (endSymbol != null && bEnd)
3130
                {
3131
                    if (startSymbol != null)
3132
                    {
3133
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
3134
                        newConnector = dicVertices.First().Key;
3135
                    }
3136

    
3137
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
3138
                    placeRunInputs = new PlaceRunInputs();
3139
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
3140
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
3141
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3142
                    if (_LMConnector != null)
3143
                    {
3144
                        _LMConnector.Commit();
3145
                        RemoveConnectorForReModelingLine(newConnector);
3146
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
3147
                        ReleaseCOMObjects(_LMConnector);
3148
                    }
3149
                    ReleaseCOMObjects(placeRunInputs);
3150
                    ReleaseCOMObjects(_LMAItem);
3151
                }
3152

    
3153
                line.SPPID.ModelItemId = newConnector.ModelItemID;
3154
                ReleaseCOMObjects(newConnector);
3155
            }
3156

    
3157
            ReleaseCOMObjects(modelItem);
3158
        }
3159

    
3160
        /// <summary>
3161
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
3162
        /// </summary>
3163
        /// <param name="connector"></param>
3164
        private void RemoveConnectorForReModelingLine(LMConnector connector)
3165
        {
3166
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
3167
            foreach (var item in dicVertices)
3168
            {
3169
                if (item.Value.Count == 2)
3170
                {
3171
                    bool result = false;
3172
                    foreach (var point in item.Value)
3173
                    {
3174
                        if (point[0] < 0 || point[1] < 0)
3175
                        {
3176
                            result = true;
3177
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
3178
                            break;
3179
                        }
3180
                    }
3181

    
3182
                    if (result)
3183
                        break;
3184
                }
3185
            }
3186
            foreach (var item in dicVertices)
3187
                ReleaseCOMObjects(item.Key);
3188
        }
3189

    
3190
        /// <summary>
3191
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
3192
        /// </summary>
3193
        /// <param name="symbol"></param>
3194
        /// <param name="line"></param>
3195
        /// <returns></returns>
3196
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
3197
        {
3198
            LMSymbol _LMSymbol = null;
3199
            foreach (var connector in symbol.CONNECTORS)
3200
            {
3201
                if (connector.CONNECTEDITEM == line.UID)
3202
                {
3203
                    if (connector.Index == 0)
3204
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
3205
                    else
3206
                    {
3207
                        ChildSymbol child = null;
3208
                        foreach (var childSymbol in symbol.ChildSymbols)
3209
                        {
3210
                            if (childSymbol.Connectors.Contains(connector))
3211
                                child = childSymbol;
3212
                            else
3213
                                child = GetChildSymbolByConnector(childSymbol, connector);
3214

    
3215
                            if (child != null)
3216
                                break;
3217
                        }
3218

    
3219
                        if (child != null)
3220
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
3221
                    }
3222

    
3223
                    break;
3224
                }
3225
            }
3226

    
3227
            return _LMSymbol;
3228
        }
3229

    
3230
        /// <summary>
3231
        /// Connector를 가지고 있는 ChildSymbol Object 반환
3232
        /// </summary>
3233
        /// <param name="item"></param>
3234
        /// <param name="connector"></param>
3235
        /// <returns></returns>
3236
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3237
        {
3238
            foreach (var childSymbol in item.ChildSymbols)
3239
            {
3240
                if (childSymbol.Connectors.Contains(connector))
3241
                    return childSymbol;
3242
                else
3243
                    return GetChildSymbolByConnector(childSymbol, connector);
3244
            }
3245

    
3246
            return null;
3247
        }
3248

    
3249
        /// <summary>
3250
        /// EndBreak 모델링 메서드
3251
        /// </summary>
3252
        /// <param name="endBreak"></param>
3253
        private void EndBreakModeling(EndBreak endBreak)
3254
        {
3255
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3256
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3257

    
3258
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3259
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3260
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3261

    
3262
            if (targetLMConnector != null)
3263
            {
3264
                // LEADER Line 검사
3265
                bool leaderLine = false;
3266
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3267
                if (symbolMapping != null)
3268
                    leaderLine = symbolMapping.LEADERLINE;
3269

    
3270
                SegmentLocation location;
3271
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3272
                Array array = null;
3273
                if (point != null)
3274
                    array = new double[] { 0, point[0], point[1] };
3275
                else
3276
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3277

    
3278
                LMLabelPersist _LmLabelPersist;
3279

    
3280
                Property property = endBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Freeze");
3281
                if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3282
                {
3283
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, Rotation: endBreak.ANGLE, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3284
                }
3285
                else
3286
                {
3287
                    _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3288
                }
3289
                
3290
                if (_LmLabelPersist != null)
3291
                {
3292
                    _LmLabelPersist.Commit();
3293
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3294
                    if (_LmLabelPersist.ModelItemObject != null)
3295
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3296
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3297

    
3298
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3299

    
3300
                    // end break arrange
3301
                    if (property == null || string.IsNullOrEmpty(property.VALUE) || !property.VALUE.Equals("True"))
3302
                    {
3303
                        MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3304
                    }
3305

    
3306
                    ReleaseCOMObjects(_LmLabelPersist);
3307
                }
3308
                ReleaseCOMObjects(targetLMConnector);
3309
            }
3310
            else
3311
            {
3312
                Log.Write("End Break UID : " + endBreak.UID);
3313
                Log.Write("Can't find targetLMConnector");
3314
            }
3315
        }
3316

    
3317
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3318
        {
3319
            double x = 0, y = 0;
3320
            if (location.HasFlag(SegmentLocation.Up))
3321
                y = GridSetting.GetInstance().Length * 3;
3322
            else if (location.HasFlag(SegmentLocation.Down))
3323
                y = -GridSetting.GetInstance().Length * 3;
3324

    
3325
            if (location.HasFlag(SegmentLocation.Right))
3326
                x = GridSetting.GetInstance().Length * 3;
3327
            else if (location.HasFlag(SegmentLocation.Left))
3328
                x = -GridSetting.GetInstance().Length * 3;
3329

    
3330
            if (x != 0 || y != 0)
3331
            {
3332
                radApp.ActiveSelectSet.RemoveAll();
3333
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3334
                if (dependency != null)
3335
                {
3336
                    radApp.ActiveSelectSet.Add(dependency);
3337
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3338
                    transform.DefineByMove2d(x, y);
3339
                    radApp.ActiveSelectSet.Transform(transform, true);
3340
                    radApp.ActiveSelectSet.RemoveAll();
3341
                }
3342
            }
3343
        }
3344

    
3345
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3346
        {
3347
            string symbolPath = string.Empty;
3348
            #region get symbol path
3349
            if (string.IsNullOrEmpty(changeSymbolPath))
3350
            {
3351
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3352
                symbolPath = GetSPPIDFileName(modelItem);
3353
                ReleaseCOMObjects(modelItem);
3354
            }
3355
            else
3356
                symbolPath = changeSymbolPath;
3357

    
3358
            #endregion
3359

    
3360
            LMConnector newConnector = null;
3361
            dynamic OID = connector.get_GraphicOID().ToString();
3362
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3363
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3364
            int verticesCount = lineStringGeometry.VertexCount;
3365
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3366
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3367

    
3368
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3369
            {
3370
                double[] vertices = null;
3371
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3372
                double x = 0;
3373
                double y = 0;
3374
                lineStringGeometry.GetVertex(1, ref x, ref y);
3375

    
3376
                string flowDirection = string.Empty;
3377
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3378
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3379
                    flowDirection = flowAttribute.get_Value().ToString();
3380

    
3381
                if (flowDirection == "End 1 is downstream (Outlet)")
3382
                {
3383
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3384
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3385
                    flowDirection = "End 1 is upstream (Inlet)";
3386
                }
3387
                else
3388
                {
3389
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3390
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3391
                }
3392
                string oldModelItemId = connector.ModelItemID;
3393
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3394
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3395
                newConnector.Commit();
3396
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3397
                if (!string.IsNullOrEmpty(flowDirection))
3398
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3399
                ReleaseCOMObjects(connector);
3400

    
3401
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3402
                {
3403
                    foreach (var repId in line.SPPID.Representations)
3404
                    {
3405
                        LMConnector _connector = dataSource.GetConnector(repId);
3406
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3407
                        {
3408
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3409
                            {
3410
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3411
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3412
                            }
3413
                        }
3414
                        ReleaseCOMObjects(_connector);
3415
                        _connector = null;
3416
                    }
3417
                }
3418
            }
3419

    
3420
            return newConnector;
3421
        }
3422

    
3423
        /// <summary>
3424
        /// SpecBreak Modeling 메서드
3425
        /// </summary>
3426
        /// <param name="specBreak"></param>
3427
        private void SpecBreakModeling(SpecBreak specBreak)
3428
        {
3429
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3430
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3431

    
3432
            if (upStreamObj != null &&
3433
                downStreamObj != null)
3434
            {
3435
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3436
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) &&
3437
                    targetLMConnector != null &&
3438
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3439
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3440

    
3441
                if (targetLMConnector != null)
3442
                {
3443
                    foreach (var attribute in specBreak.ATTRIBUTES)
3444
                    {
3445
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3446
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3447
                        {
3448
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3449
                            SegmentLocation location;
3450
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3451
                            Array array = null;
3452
                            if (point != null)
3453
                                array = new double[] { 0, point[0], point[1] };
3454
                            else
3455
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3456
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, null, null, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3457

    
3458
                            if (_LmLabelPersist != null)
3459
                            {
3460
                                _LmLabelPersist.Commit();
3461
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3462
                                if (_LmLabelPersist.ModelItemObject != null)
3463
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3464
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3465

    
3466
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3467

    
3468
                                // spec break arrange
3469
                                MoveSegmentBreak(_LmLabelPersist.RepresentationObject.Id, _LmLabelPersist);
3470

    
3471
                                ReleaseCOMObjects(_LmLabelPersist);
3472
                            }
3473
                        }
3474
                    }
3475

    
3476
                    Property property = specBreak.PROPERTIES.Find(loop => loop.ATTRIBUTE == "Show");
3477
                    if (property != null && !string.IsNullOrEmpty(property.VALUE) && property.VALUE.Equals("True"))
3478
                    {
3479
                        // temp
3480
                        ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3481
                    }
3482
                    ReleaseCOMObjects(targetLMConnector);
3483
                }
3484
                else
3485
                {
3486
                    Log.Write("Spec Break UID : " + specBreak.UID);
3487
                    Log.Write("Can't find targetLMConnector");
3488
                }
3489
            }
3490
        }
3491

    
3492
        private bool IsRhombus(LMLabelPersist labelPersist, out double x, out double y, out double radius)
3493
        {
3494
            bool result = false;
3495
            x = 0; y = 0; radius = 0;
3496

    
3497
            string oid = labelPersist.get_GraphicOID().ToString();
3498
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3499

    
3500
            if (dependency != null)
3501
            {
3502
                bool isLabel = false;
3503
                foreach (var attributes in dependency.AttributeSets)
3504
                {
3505
                    foreach (var attribute in attributes)
3506
                    {
3507
                        string name = attribute.Name;
3508
                        string value = attribute.GetValue().ToString();
3509
                        if (name == "DrawingItemType" && value == "LabelPersist")
3510
                        {
3511
                            isLabel = true;
3512
                            break;
3513
                        }
3514
                    }
3515
                }
3516
                if (isLabel)
3517
                {
3518
                    double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
3519
                    foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
3520
                    {
3521
                        if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLine2d)
3522
                        {
3523
                            Ingr.RAD2D.Line2d line2D = drawingObject as Ingr.RAD2D.Line2d;
3524

    
3525
                            double x1, y1, x2, y2;
3526
                            line2D.GetStartPoint(out x1, out y1);
3527
                            line2D.GetEndPoint(out x2, out y2);
3528
                            double tX1 = Math.Min(x1, x2), tY1 = Math.Min(y1, y2), tX2 = Math.Max(x1, x2), tY2 = Math.Max(y1, y2);
3529
                            if (minX > tX1)
3530
                                minX = tX1;
3531
                            if (minY > tY1)
3532
                                minY = tY1;
3533
                            if (maxX < tX2)
3534
                                maxX = tX2;
3535
                            if (maxY < tY2)
3536
                                maxY = tY2;
3537
                        }
3538
                    }
3539

    
3540
                    double width = Math.Abs(maxX - minX);
3541
                    double height = Math.Abs(maxY - minY);
3542
                    double ratio = width / height * 100;
3543
                    if (ratio > 99d && ratio < 101d)
3544
                    {
3545
                        result = true;
3546
                    }
3547
                    x = (maxX + minX) / 2d;
3548
                    y = (maxY + minY) / 2d;
3549
                    radius = width / 2d;
3550
                }
3551
            }
3552

    
3553
            return result;
3554
        }
3555

    
3556
        private void MoveSegmentBreak(string connectorID, LMLabelPersist labelPersist)
3557
        {
3558
            bool bFind = false;
3559
            double x, y, radius;
3560
            if (IsRhombus(labelPersist, out x, out y, out radius))
3561
            {
3562
                List<double[]> itemPoints = new List<double[]>();
3563
                LMConnector connector = dataSource.GetConnector(connectorID);
3564
                foreach (LMLabelPersist label in connector.LabelPersists)
3565
                {
3566
                    if (!"Active".Equals(label.get_ItemStatus()))
3567
                        continue;
3568

    
3569
                    if (!label.Id.Equals(labelPersist.Id))
3570
                    {
3571
                        double centerX, centerY, temp;
3572
                        if (IsRhombus(label, out centerX, out centerY, out temp))
3573
                        {
3574
                            bFind = true;
3575
                            itemPoints.Add(new double[] { centerX, centerY });
3576
                        }
3577
                    }
3578
                }
3579
                ReleaseCOMObjects(connector);
3580

    
3581

    
3582
                if (bFind)
3583
                {
3584
                    double[] startPoint = itemPoints.First();
3585
                    itemPoints.RemoveAt(0);
3586

    
3587
                    for (int i = 0; i < 8; i++)
3588
                    {
3589
                        double pointX = 0, pointY = 0;
3590
                        switch (i)
3591
                        {
3592
                            case 0:
3593
                                pointX = startPoint[0] + radius;
3594
                                pointY = startPoint[1] + radius;
3595
                                break;
3596
                            case 1:
3597
                                pointX = startPoint[0] + radius + radius;
3598
                                pointY = startPoint[1];
3599
                                break;
3600
                            case 2:
3601
                                pointX = startPoint[0] + radius;
3602
                                pointY = startPoint[1] - radius;
3603
                                break;
3604
                            case 3:
3605
                                pointX = startPoint[0];
3606
                                pointY = startPoint[1] - radius - radius;
3607
                                break;
3608
                            case 4:
3609
                                pointX = startPoint[0] - radius;
3610
                                pointY = startPoint[1] - radius;
3611
                                break;
3612
                            case 5:
3613
                                pointX = startPoint[0] - radius - radius;
3614
                                pointY = startPoint[1];
3615
                                break;
3616
                            case 6:
3617
                                pointX = startPoint[0] - radius;
3618
                                pointY = startPoint[1] + radius;
3619
                                break;
3620
                            case 7:
3621
                                pointX = startPoint[0];
3622
                                pointY = startPoint[1] + radius + radius;
3623
                                break;
3624
                            default:
3625
                                break;
3626
                        }
3627

    
3628
                        if (!ExistSegmentByPoint(pointX, pointY))
3629
                        {
3630
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
3631
                            if (dependency != null)
3632
                            {
3633
                                radApp.ActiveSelectSet.RemoveAll();
3634
                                radApp.ActiveSelectSet.Add(dependency);
3635
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3636
                                transform.DefineByMove2d(pointX - x, pointY - y);
3637
                                radApp.ActiveSelectSet.Transform(transform, true);
3638
                                radApp.ActiveSelectSet.RemoveAll();
3639
                            }
3640
                            break;
3641
                        }
3642
                    }
3643

    
3644
                    bool ExistSegmentByPoint(double pointX, double pointY)
3645
                    {
3646
                        bool result = false;
3647
                        foreach (var item in itemPoints)
3648
                        {
3649
                            double distance = SPPIDUtil.CalcPointToPointdDistance(item[0], item[1], pointX, pointY);
3650
                            if (Math.Truncate(distance * 1000000000d).Equals(0))
3651
                                result = true;
3652
                        }
3653
                        return result;
3654
                    }
3655
                }
3656
            }
3657

    
3658
            if (!bFind)
3659
                MoveSegmentBestLocation(labelPersist.get_GraphicOID().ToString(), new double[] { x - radius, y - radius, x + radius, y + radius }, itemRange);
3660
        }
3661

    
3662
        LMConnectors GetConnectors()
3663
        {
3664
            LMAFilter filter = new LMAFilter();
3665
            LMACriterion criterion1 = new LMACriterion();
3666
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3667
            criterion1.Operator = "=";
3668
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3669
            criterion1.Conjunctive = true;
3670
            filter.get_Criteria().Add(criterion1);
3671
            filter.ItemType = "Connector";
3672

    
3673
            LMACriterion criterion2 = new LMACriterion();
3674
            criterion2.SourceAttributeName = "ITEMSTATUS";
3675
            criterion2.Operator = "=";
3676
            criterion2.set_ValueAttribute("1");
3677
            criterion2.Conjunctive = true;
3678
            filter.get_Criteria().Add(criterion2);
3679

    
3680
            LMACriterion criterion3 = new LMACriterion();
3681
            criterion3.SourceAttributeName = "INSTOCKPILE";
3682
            criterion3.Operator = "=";
3683
            criterion3.set_ValueAttribute("1");
3684
            criterion3.Conjunctive = true;
3685
            filter.get_Criteria().Add(criterion3);
3686

    
3687
            LMConnectors items = new LMConnectors();
3688
            items.Collect(dataSource, Filter: filter);
3689

    
3690
            ReleaseCOMObjects(filter);
3691
            ReleaseCOMObjects(criterion1);
3692
            ReleaseCOMObjects(criterion2);
3693
            ReleaseCOMObjects(criterion3);
3694

    
3695
            return items;
3696
        }
3697
        LMSymbols GetSymbols()
3698
        {
3699
            LMAFilter filter = new LMAFilter();
3700
            LMACriterion criterion1 = new LMACriterion();
3701
            criterion1.SourceAttributeName = "SP_DRAWINGID";
3702
            criterion1.Operator = "=";
3703
            criterion1.set_ValueAttribute(dataSource.PIDMgr.Drawing.ID);
3704
            criterion1.Conjunctive = true;
3705
            filter.get_Criteria().Add(criterion1);
3706
            filter.ItemType = "Symbol";
3707

    
3708
            LMACriterion criterion2 = new LMACriterion();
3709
            criterion2.SourceAttributeName = "ITEMSTATUS";
3710
            criterion2.Operator = "=";
3711
            criterion2.set_ValueAttribute("1");
3712
            criterion2.Conjunctive = true;
3713
            filter.get_Criteria().Add(criterion2);
3714

    
3715
            LMACriterion criterion3 = new LMACriterion();
3716
            criterion3.SourceAttributeName = "INSTOCKPILE";
3717
            criterion3.Operator = "=";
3718
            criterion3.set_ValueAttribute("1");
3719
            criterion3.Conjunctive = true;
3720
            filter.get_Criteria().Add(criterion3);
3721

    
3722
            LMSymbols items = new LMSymbols();
3723
            items.Collect(dataSource, Filter: filter);
3724

    
3725
            ReleaseCOMObjects(filter);
3726
            ReleaseCOMObjects(criterion1);
3727
            ReleaseCOMObjects(criterion2);
3728
            ReleaseCOMObjects(criterion3);
3729

    
3730
            return items;
3731
        }
3732

    
3733
        private void SetConnectorAndSymbolRange()
3734
        {
3735
            itemRange = new List<double[]>();
3736

    
3737
            LMConnectors connectors = GetConnectors();
3738
            foreach (LMConnector connector in connectors)
3739
            {
3740
                List<double[]> vertices = GetConnectorVertices(connector);
3741
                for (int i = 0; i < vertices.Count - 1; i++)
3742
                {
3743
                    double[] point1 = vertices[i];
3744
                    double[] point2 = vertices[i + 1];
3745
                    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]);
3746
                    double gap = 0.0001d;
3747
                    itemRange.Add(new double[] { x1 - gap, y1 - gap, x2 + gap, y2 + gap });
3748
                }
3749
                ReleaseCOMObjects(connector);
3750
            }
3751
            ReleaseCOMObjects(connectors);
3752

    
3753
            LMSymbols symbols = GetSymbols();
3754
            foreach (LMSymbol symbol in symbols)
3755
            {
3756
                string oid = symbol.get_GraphicOID().ToString();
3757
                DrawingObjectBase drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid];
3758
                if (drawingObject != null)
3759
                {
3760
                    double x1, y1, x2, y2;
3761
                    drawingObject.Range(out x1, out y1, out x2, out y2);
3762
                    itemRange.Add(new double[] { x1, y1, x2, y2 });
3763
                }
3764

    
3765
                ReleaseCOMObjects(symbol);
3766
            }
3767
            ReleaseCOMObjects(symbols);
3768
        }
3769

    
3770
        private void MoveSegmentBestLocation(string oid, double[] segmentRange, List<double[]> allRanges)
3771
        {
3772
            double minValue = Math.Min(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3773
            double maxValue = Math.Max(segmentRange[2] - segmentRange[0], segmentRange[3] - segmentRange[1]);
3774

    
3775
            double maxX = 0, maxY = 0;
3776
            maxX = maxValue * 10;
3777
            maxY = minValue * 10;
3778

    
3779
            double move = minValue / 10d;
3780
            double textGap = minValue / 3d;
3781
            segmentRange = new double[] { segmentRange[0] - textGap, segmentRange[1] - textGap, segmentRange[2] + textGap, segmentRange[3] + textGap };
3782

    
3783

    
3784
            List<double[]> containRanges = new List<double[]>();
3785
            double[] findRange = new double[] {
3786
            segmentRange[0] - maxX, segmentRange[1] - maxY,
3787
            segmentRange[2] + maxX, segmentRange[3] + maxY};
3788

    
3789
            foreach (var range in allRanges)
3790
                if (SPPIDUtil.IsOverlap(findRange, range))
3791
                    containRanges.Add(range);
3792

    
3793
            double movePointX = 0, movePointY = 0, distance = double.MaxValue;
3794
            for (double x = 0; x < maxX; x = x + move)
3795
                for (double y = 0; y < maxY; y = y + move)
3796
                    for (int i = 0; i < 4; i++)
3797
                    {
3798
                        double tempX = 0d, tempY = 0d;
3799
                        switch (i)
3800
                        {
3801
                            case 0:
3802
                                tempX = x;
3803
                                tempY = y;
3804
                                break;
3805
                            case 1:
3806
                                tempX = -x;
3807
                                tempY = y;
3808
                                break;
3809
                            case 2:
3810
                                tempX = -x;
3811
                                tempY = -y;
3812
                                break;
3813
                            case 3:
3814
                                tempX = x;
3815
                                tempY = -y;
3816
                                break;
3817
                            default:
3818
                                break;
3819
                        }
3820

    
3821
                        bool result = true;
3822
                        double[] movedRange = new double[] { segmentRange[0] + tempX, segmentRange[1] + tempY, segmentRange[2] + tempX, segmentRange[3] + tempY };
3823
                        foreach (double[] range in containRanges)
3824
                        {
3825
                            if (SPPIDUtil.IsOverlap(range, movedRange))
3826
                            {
3827
                                result = false;
3828
                                break;
3829
                            }
3830
                        }
3831

    
3832
                        if (result)
3833
                        {
3834
                            //double tempDistance = Utils.CalcDistance(new double[] { 0, 0, 0 }, new double[] { tempX, tempY, 0 });
3835
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(0, 0, tempX, tempY);
3836
                            bool bChange = false;
3837
                            if (distance > tempDistance)
3838
                                bChange = true;
3839
                            else if (distance.Equals(tempDistance) && (movePointX.Equals(0d) || movePointY.Equals(0d)))
3840
                                bChange = true;
3841

    
3842
                            if (bChange)
3843
                            {
3844
                                distance = tempDistance;
3845
                                movePointX = tempX;
3846
                                movePointY = tempY;
3847
                            }
3848
                        }
3849
                    }
3850

    
3851
            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[oid] as DependencyObject;
3852
            if (dependency != null)
3853
            {
3854
                radApp.ActiveSelectSet.RemoveAll();
3855
                radApp.ActiveSelectSet.Add(dependency);
3856
                Ingr.RAD2D.Transform transform = dependency.GetTransform();
3857
                transform.DefineByMove2d(movePointX, movePointY);
3858
                radApp.ActiveSelectSet.Transform(transform, true);
3859
                radApp.ActiveSelectSet.RemoveAll();
3860
            }
3861
        }
3862

    
3863
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3864
        {
3865
            LMConnector targetConnector = null;
3866
            Symbol targetSymbol = targetObj as Symbol;
3867
            Symbol connectedSymbol = connectedObj as Symbol;
3868
            Line targetLine = targetObj as Line;
3869
            Line connectedLine = connectedObj as Line;
3870
            if (targetSymbol != null && connectedSymbol != null)
3871
            {
3872
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3873
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3874

    
3875
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3876
                {
3877
                    if (connector.get_ItemStatus() != "Active")
3878
                        continue;
3879

    
3880
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3881
                    {
3882
                        targetConnector = connector;
3883
                        break;
3884
                    }
3885
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3886
                    {
3887
                        targetConnector = connector;
3888
                        break;
3889
                    }
3890
                }
3891

    
3892
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3893
                {
3894
                    if (connector.get_ItemStatus() != "Active")
3895
                        continue;
3896

    
3897
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3898
                    {
3899
                        targetConnector = connector;
3900
                        break;
3901
                    }
3902
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3903
                    {
3904
                        targetConnector = connector;
3905
                        break;
3906
                    }
3907
                }
3908

    
3909
                ReleaseCOMObjects(targetLMSymbol);
3910
                ReleaseCOMObjects(connectedLMSymbol);
3911
            }
3912
            else if (targetLine != null && connectedLine != null)
3913
            {
3914
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3915
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3916

    
3917
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3918
                {
3919
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3920
                    {
3921
                        if (targetConnector != null)
3922
                            break;
3923

    
3924
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3925
                        {
3926
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3927

    
3928
                            if (IsConnected(_LMConnector, connectedModelItem))
3929
                                targetConnector = _LMConnector;
3930
                            else
3931
                                ReleaseCOMObjects(_LMConnector);
3932
                        }
3933
                    }
3934

    
3935
                    ReleaseCOMObjects(targetModelItem);
3936
                }
3937
            }
3938
            else
3939
            {
3940
                LMSymbol connectedLMSymbol = null;
3941
                if (connectedSymbol != null)
3942
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3943
                else if (targetSymbol != null)
3944
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3945
                else
3946
                {
3947

    
3948
                }
3949
                LMModelItem targetModelItem = null;
3950
                if (targetLine != null)
3951
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3952
                else if (connectedLine != null)
3953
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3954
                else
3955
                {
3956

    
3957
                }
3958
                if (connectedLMSymbol != null && targetModelItem != null)
3959
                {
3960
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3961
                    {
3962
                        if (connector.get_ItemStatus() != "Active")
3963
                            continue;
3964

    
3965
                        if (IsConnected(connector, targetModelItem))
3966
                        {
3967
                            targetConnector = connector;
3968
                            break;
3969
                        }
3970
                    }
3971

    
3972
                    if (targetConnector == null)
3973
                    {
3974
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3975
                        {
3976
                            if (connector.get_ItemStatus() != "Active")
3977
                                continue;
3978

    
3979
                            if (IsConnected(connector, targetModelItem))
3980
                            {
3981
                                targetConnector = connector;
3982
                                break;
3983
                            }
3984
                        }
3985
                    }
3986
                }
3987

    
3988
            }
3989

    
3990
            return targetConnector;
3991
        }
3992

    
3993
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
3994
        {
3995
            double[] result = null;
3996
            Line targetLine = targetObj as Line;
3997
            Symbol targetSymbol = targetObj as Symbol;
3998
            Line connLine = connObj as Line;
3999
            Symbol connSymbol = connObj as Symbol;
4000
            location = SegmentLocation.None;
4001
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
4002
            {
4003
                result = GetConnectorVertices(targetConnector)[0];
4004
                if (targetSymbol != null && connSymbol != null)
4005
                {
4006
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
4007
                    result = new double[] { result[0], result[1] };
4008
                    if (slopeType == SlopeType.HORIZONTAL)
4009
                        location = SegmentLocation.Up;
4010
                    else if (slopeType == SlopeType.VERTICAL)
4011
                        location = SegmentLocation.Right;
4012
                }
4013
                else if (targetLine != null)
4014
                {
4015
                    result = new double[] { result[0], result[1] };
4016
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4017
                        location = SegmentLocation.Up;
4018
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
4019
                        location = SegmentLocation.Right;
4020
                }
4021
                else if (connLine != null)
4022
                {
4023
                    result = new double[] { result[0], result[1] };
4024
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
4025
                        location = SegmentLocation.Up;
4026
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
4027
                        location = SegmentLocation.Right;
4028
                }
4029
            }
4030
            else
4031
            {
4032
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
4033
                {
4034
                    Line line = connObj as Line;
4035
                    LMConnector connectedConnector = null;
4036
                    int connIndex = 0;
4037
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4038
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
4039

    
4040
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
4041

    
4042
                    ReleaseCOMObjects(modelItem);
4043
                    ReleaseCOMObjects(connectedConnector);
4044

    
4045
                    if (vertices.Count > 0)
4046
                    {
4047
                        if (connIndex == 1)
4048
                            result = vertices[0];
4049
                        else if (connIndex == 2)
4050
                            result = vertices[vertices.Count - 1];
4051

    
4052
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4053
                        {
4054
                            result = new double[] { result[0], result[1] };
4055
                            location = SegmentLocation.Up;
4056
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4057
                                location = location | SegmentLocation.Right;
4058
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4059
                                location = location | SegmentLocation.Left;
4060
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
4061
                                location = location | SegmentLocation.Left;
4062
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
4063
                                location = location | SegmentLocation.Right;
4064
                        }
4065
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
4066
                        {
4067
                            result = new double[] { result[0], result[1] };
4068
                            location = SegmentLocation.Right;
4069
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4070
                                location = location | SegmentLocation.Up;
4071
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4072
                                location = location | SegmentLocation.Down;
4073
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
4074
                                location = location | SegmentLocation.Down;
4075
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
4076
                                location = location | SegmentLocation.Up;
4077
                        }
4078

    
4079
                    }
4080
                }
4081
                else
4082
                {
4083
                    Log.Write("error in GetSegemtPoint");
4084
                }
4085
            }
4086

    
4087
            return result;
4088
        }
4089

    
4090
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
4091
        {
4092
            bool result = false;
4093

    
4094
            foreach (LMRepresentation rep in modelItem.Representations)
4095
            {
4096
                if (result)
4097
                    break;
4098

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

    
4103
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4104
                        connector.ConnectItem1SymbolObject != null &&
4105
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4106
                    {
4107
                        result = true;
4108
                        ReleaseCOMObjects(_LMConnector);
4109
                        break;
4110
                    }
4111
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4112
                        connector.ConnectItem2SymbolObject != null &&
4113
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4114
                    {
4115
                        result = true;
4116
                        ReleaseCOMObjects(_LMConnector);
4117
                        break;
4118
                    }
4119
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4120
                        connector.ConnectItem1SymbolObject != null &&
4121
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4122
                    {
4123
                        result = true;
4124
                        ReleaseCOMObjects(_LMConnector);
4125
                        break;
4126
                    }
4127
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4128
                        connector.ConnectItem2SymbolObject != null &&
4129
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4130
                    {
4131
                        result = true;
4132
                        ReleaseCOMObjects(_LMConnector);
4133
                        break;
4134
                    }
4135

    
4136
                    ReleaseCOMObjects(_LMConnector);
4137
                }
4138
            }
4139

    
4140

    
4141
            return result;
4142
        }
4143

    
4144
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
4145
        {
4146
            foreach (LMRepresentation rep in modelItem.Representations)
4147
            {
4148
                if (connectedConnector != null)
4149
                    break;
4150

    
4151
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4152
                {
4153
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4154

    
4155
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
4156
                        connector.ConnectItem1SymbolObject != null &&
4157
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4158
                    {
4159
                        connectedConnector = _LMConnector;
4160
                        connectorIndex = 1;
4161
                        break;
4162
                    }
4163
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
4164
                        connector.ConnectItem2SymbolObject != null &&
4165
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4166
                    {
4167
                        connectedConnector = _LMConnector;
4168
                        connectorIndex = 2;
4169
                        break;
4170
                    }
4171
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4172
                        connector.ConnectItem1SymbolObject != null &&
4173
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
4174
                    {
4175
                        connectedConnector = _LMConnector;
4176
                        connectorIndex = 1;
4177
                        break;
4178
                    }
4179
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
4180
                        connector.ConnectItem2SymbolObject != null &&
4181
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
4182
                    {
4183
                        connectedConnector = _LMConnector;
4184
                        connectorIndex = 2;
4185
                        break;
4186
                    }
4187

    
4188
                    if (connectedConnector == null)
4189
                        ReleaseCOMObjects(_LMConnector);
4190
                }
4191
            }
4192
        }
4193

    
4194
        /// <summary>
4195
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
4196
        /// </summary>
4197
        /// <param name="modelItemID1"></param>
4198
        /// <param name="modelItemID2"></param>
4199
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
4200
        {
4201
            try
4202
            {
4203
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
4204
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
4205
                List<double[]> vertices1 = null;
4206
                string graphicOID1 = string.Empty;
4207
                if (connector1 != null)
4208
                {
4209
                    vertices1 = GetConnectorVertices(connector1);
4210
                    graphicOID1 = connector1.get_GraphicOID();
4211
                }
4212
                _LMAItem item1 = modelItem1.AsLMAItem();
4213
                ReleaseCOMObjects(connector1);
4214
                connector1 = null;
4215

    
4216
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
4217
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
4218
                List<double[]> vertices2 = null;
4219
                string graphicOID2 = string.Empty;
4220
                if (connector2 != null)
4221
                {
4222
                    vertices2 = GetConnectorVertices(connector2);
4223
                    graphicOID2 = connector2.get_GraphicOID();
4224
                }
4225
                _LMAItem item2 = modelItem2.AsLMAItem();
4226
                ReleaseCOMObjects(connector2);
4227
                connector2 = null;
4228

    
4229
                // item2가 item1으로 조인
4230
                _placement.PIDJoinRuns(ref item1, ref item2);
4231
                item1.Commit();
4232
                item2.Commit();
4233

    
4234
                string beforeID = string.Empty;
4235
                string afterID = string.Empty;
4236

    
4237
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
4238
                {
4239
                    beforeID = modelItem2.Id;
4240
                    afterID = modelItem1.Id;
4241
                    survivorId = afterID;
4242
                }
4243
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
4244
                {
4245
                    beforeID = modelItem1.Id;
4246
                    afterID = modelItem2.Id;
4247
                    survivorId = afterID;
4248
                }
4249
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
4250
                {
4251
                    int model1Cnt = GetConnectorCount(modelId1);
4252
                    int model2Cnt = GetConnectorCount(modelId2);
4253
                    if (model1Cnt == 0)
4254
                    {
4255
                        beforeID = modelItem1.Id;
4256
                        afterID = modelItem2.Id;
4257
                        survivorId = afterID;
4258
                    }
4259
                    else if (model2Cnt == 0)
4260
                    {
4261
                        beforeID = modelItem2.Id;
4262
                        afterID = modelItem1.Id;
4263
                        survivorId = afterID;
4264
                    }
4265
                    else
4266
                        survivorId = null;
4267
                }
4268
                else
4269
                {
4270
                    Log.Write("잘못된 경우");
4271
                    survivorId = null;
4272
                }
4273

    
4274
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
4275
                {
4276
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
4277
                    foreach (var line in lines)
4278
                        line.SPPID.ModelItemId = afterID;
4279
                }
4280

    
4281
                ReleaseCOMObjects(modelItem1);
4282
                ReleaseCOMObjects(item1);
4283
                ReleaseCOMObjects(modelItem2);
4284
                ReleaseCOMObjects(item2);
4285
            }
4286
            catch (Exception ex)
4287
            {
4288
                Log.Write("Join Error");
4289
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
4290
            }
4291
        }
4292

    
4293
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
4294
        {
4295
            bool result = false;
4296
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
4297
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
4298
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
4299

    
4300
            foreach (var item in endBreaks)
4301
            {
4302
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
4303
                {
4304
                    result = true;
4305
                    break;
4306
                }
4307
            }
4308

    
4309
            return result;
4310
        }
4311
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
4312
        {
4313
            List<string> temp = new List<string>();
4314
            List<LMConnector> connectors = new List<LMConnector>();
4315
            foreach (LMConnector connector in symbol.Avoid1Connectors)
4316
            {
4317
                if (connector.get_ItemStatus() != "Active")
4318
                    continue;
4319

    
4320
                LMModelItem modelItem = connector.ModelItemObject;
4321
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4322
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4323
                    temp.Add(modelItem.Id);
4324

    
4325
                if (temp.Contains(modelItem.Id) &&
4326
                    connOtherSymbol != null &&
4327
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4328
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4329
                    temp.Remove(modelItem.Id);
4330

    
4331

    
4332
                if (temp.Contains(modelItem.Id))
4333
                    connectors.Add(connector);
4334
                ReleaseCOMObjects(connOtherSymbol);
4335
                connOtherSymbol = null;
4336
                ReleaseCOMObjects(modelItem);
4337
                modelItem = null;
4338
            }
4339

    
4340
            foreach (LMConnector connector in symbol.Avoid2Connectors)
4341
            {
4342
                if (connector.get_ItemStatus() != "Active")
4343
                    continue;
4344

    
4345
                LMModelItem modelItem = connector.ModelItemObject;
4346
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
4347
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
4348
                    temp.Add(modelItem.Id);
4349

    
4350
                if (temp.Contains(modelItem.Id) &&
4351
                    connOtherSymbol != null &&
4352
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
4353
                    Convert.ToBoolean(connector.get_IsZeroLength()))
4354
                    temp.Remove(modelItem.Id);
4355

    
4356
                if (temp.Contains(modelItem.Id))
4357
                    connectors.Add(connector);
4358
                ReleaseCOMObjects(connOtherSymbol);
4359
                connOtherSymbol = null;
4360
                ReleaseCOMObjects(modelItem);
4361
                modelItem = null;
4362
            }
4363

    
4364

    
4365
            List<string> result = new List<string>();
4366
            string originalName = GetSPPIDFileName(modelId);
4367
            foreach (var connector in connectors)
4368
            {
4369
                string fileName = GetSPPIDFileName(connector.ModelItemID);
4370
                if (originalName == fileName)
4371
                    result.Add(connector.ModelItemID);
4372
                else
4373
                {
4374
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
4375
                        result.Add(connector.ModelItemID);
4376
                    else
4377
                    {
4378
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
4379
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
4380
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
4381
                            result.Add(connector.ModelItemID);
4382
                    }
4383
                }
4384
            }
4385

    
4386
            foreach (var connector in connectors)
4387
                ReleaseCOMObjects(connector);
4388

    
4389
            return result;
4390

    
4391

    
4392
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
4393
            {
4394
                LMSymbol findResult = null;
4395
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
4396
                    findResult = connector.ConnectItem1SymbolObject;
4397
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
4398
                    findResult = connector.ConnectItem2SymbolObject;
4399

    
4400
                return findResult;
4401
            }
4402
        }
4403

    
4404
        /// <summary>
4405
        /// PipeRun의 좌표를 가져오는 메서드
4406
        /// </summary>
4407
        /// <param name="modelId"></param>
4408
        /// <returns></returns>
4409
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
4410
        {
4411
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
4412
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
4413

    
4414
            if (modelItem != null)
4415
            {
4416
                foreach (LMRepresentation rep in modelItem.Representations)
4417
                {
4418
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4419
                    {
4420
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
4421
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
4422
                        {
4423
                            ReleaseCOMObjects(_LMConnector);
4424
                            _LMConnector = null;
4425
                            continue;
4426
                        }
4427
                        connectorVertices.Add(_LMConnector, new List<double[]>());
4428
                        dynamic OID = rep.get_GraphicOID().ToString();
4429
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4430
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4431
                        int verticesCount = lineStringGeometry.VertexCount;
4432
                        double[] vertices = null;
4433
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
4434
                        for (int i = 0; i < verticesCount; i++)
4435
                        {
4436
                            double x = 0;
4437
                            double y = 0;
4438
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4439
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
4440
                        }
4441
                    }
4442
                }
4443

    
4444
                ReleaseCOMObjects(modelItem);
4445
            }
4446

    
4447
            return connectorVertices;
4448
        }
4449

    
4450
        private List<double[]> GetConnectorVertices(LMConnector connector)
4451
        {
4452
            List<double[]> vertices = new List<double[]>();
4453
            if (connector != null)
4454
            {
4455
                dynamic OID = connector.get_GraphicOID().ToString();
4456
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4457
                if (drawingObject != null)
4458
                {
4459
                    Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4460
                    int verticesCount = lineStringGeometry.VertexCount;
4461
                    double[] value = null;
4462
                    lineStringGeometry.GetVertices(ref verticesCount, ref value);
4463
                    for (int i = 0; i < verticesCount; i++)
4464
                    {
4465
                        double x = 0;
4466
                        double y = 0;
4467
                        lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4468
                        vertices.Add(new double[] { x, y });
4469
                    }
4470
                }
4471
            }
4472
            return vertices;
4473
        }
4474

    
4475
        private double GetConnectorDistance(LMConnector connector)
4476
        {
4477
            double result = 0;
4478
            List<double[]> vertices = new List<double[]>();
4479
            if (connector != null)
4480
            {
4481
                dynamic OID = connector.get_GraphicOID().ToString();
4482
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4483
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4484
                int verticesCount = lineStringGeometry.VertexCount;
4485
                double[] value = null;
4486
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4487
                for (int i = 0; i < verticesCount; i++)
4488
                {
4489
                    double x = 0;
4490
                    double y = 0;
4491
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4492
                    vertices.Add(new double[] { x, y });
4493
                    if (vertices.Count > 1)
4494
                    {
4495
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
4496
                    }
4497
                }
4498
            }
4499
            return result;
4500
        }
4501
        private double[] GetConnectorRange(LMConnector connector)
4502
        {
4503
            double[] result = null;
4504
            List<double[]> vertices = new List<double[]>();
4505
            if (connector != null)
4506
            {
4507
                dynamic OID = connector.get_GraphicOID().ToString();
4508
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
4509
                double minX = 0;
4510
                double minY = 0;
4511
                double maxX = 0;
4512
                double maxY = 0;
4513

    
4514
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
4515
                result = new double[] { minX, minY, maxX, maxY };
4516
            }
4517
            return result;
4518
        }
4519
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
4520
        {
4521
            List<double[]> vertices = null;
4522
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
4523
            if (drawingObject != null)
4524
            {
4525
                vertices = new List<double[]>();
4526
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
4527
                int verticesCount = lineStringGeometry.VertexCount;
4528
                double[] value = null;
4529
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
4530
                for (int i = 0; i < verticesCount; i++)
4531
                {
4532
                    double x = 0;
4533
                    double y = 0;
4534
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
4535
                    vertices.Add(new double[] { x, y });
4536
                }
4537
            }
4538
            return vertices;
4539
        }
4540
        /// <summary>
4541
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
4542
        /// </summary>
4543
        /// <param name="connectorVertices"></param>
4544
        /// <param name="connX"></param>
4545
        /// <param name="connY"></param>
4546
        /// <returns></returns>
4547
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
4548
        {
4549
            double length = double.MaxValue;
4550
            LMConnector targetConnector = null;
4551
            foreach (var item in connectorVertices)
4552
            {
4553
                List<double[]> points = item.Value;
4554
                for (int i = 0; i < points.Count - 1; i++)
4555
                {
4556
                    double[] point1 = points[i];
4557
                    double[] point2 = points[i + 1];
4558
                    double x1 = Math.Min(point1[0], point2[0]);
4559
                    double y1 = Math.Min(point1[1], point2[1]);
4560
                    double x2 = Math.Max(point1[0], point2[0]);
4561
                    double y2 = Math.Max(point1[1], point2[1]);
4562

    
4563
                    if ((x1 <= connX && x2 >= connX) ||
4564
                        (y1 <= connY && y2 >= connY))
4565
                    {
4566
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
4567
                        if (length >= distance)
4568
                        {
4569
                            targetConnector = item.Key;
4570
                            length = distance;
4571
                        }
4572

    
4573
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
4574
                        if (length >= distance)
4575
                        {
4576
                            targetConnector = item.Key;
4577
                            length = distance;
4578
                        }
4579
                    }
4580
                }
4581
            }
4582

    
4583
            // 못찾았을때.
4584
            length = double.MaxValue;
4585
            if (targetConnector == null)
4586
            {
4587
                foreach (var item in connectorVertices)
4588
                {
4589
                    List<double[]> points = item.Value;
4590

    
4591
                    foreach (double[] point in points)
4592
                    {
4593
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
4594
                        if (length >= distance)
4595
                        {
4596
                            targetConnector = item.Key;
4597
                            length = distance;
4598
                        }
4599
                    }
4600
                }
4601
            }
4602

    
4603
            return targetConnector;
4604
        }
4605

    
4606
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
4607
        {
4608
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
4609
            if (vertices.Count == 0)
4610
                return null;
4611

    
4612
            double length = double.MaxValue;
4613
            LMConnector targetConnector = null;
4614
            double[] resultPoint = null;
4615
            List<double[]> targetVertices = null;
4616

    
4617
            // Vertices 포인트에 제일 가까운곳
4618
            foreach (var item in vertices)
4619
            {
4620
                List<double[]> points = item.Value;
4621
                for (int i = 0; i < points.Count; i++)
4622
                {
4623
                    double[] point = points[i];
4624
                    double tempX = point[0];
4625
                    double tempY = point[1];
4626

    
4627
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
4628
                    if (length >= distance)
4629
                    {
4630
                        targetConnector = item.Key;
4631
                        length = distance;
4632
                        resultPoint = point;
4633
                        targetVertices = item.Value;
4634
                    }
4635
                }
4636
            }
4637

    
4638
            // Vertices Cross에 제일 가까운곳
4639
            foreach (var item in vertices)
4640
            {
4641
                List<double[]> points = item.Value;
4642
                for (int i = 0; i < points.Count - 1; i++)
4643
                {
4644
                    double[] point1 = points[i];
4645
                    double[] point2 = points[i + 1];
4646

    
4647
                    double maxLineX = Math.Max(point1[0], point2[0]);
4648
                    double minLineX = Math.Min(point1[0], point2[0]);
4649
                    double maxLineY = Math.Max(point1[1], point2[1]);
4650
                    double minLineY = Math.Min(point1[1], point2[1]);
4651

    
4652
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4653

    
4654
                    double[] crossingPoint = SPPIDUtil.CalcLineCrossingPoint(line.SPPID.START_X, line.SPPID.START_Y, line.SPPID.END_X, line.SPPID.END_Y, point1[0], point1[1], point2[0], point2[1]);
4655
                    if (crossingPoint != null)
4656
                    {
4657
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4658
                        if (length >= distance)
4659
                        {
4660
                            if (slope == SlopeType.Slope &&
4661
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4662
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4663
                            {
4664
                                targetConnector = item.Key;
4665
                                length = distance;
4666
                                resultPoint = crossingPoint;
4667
                                targetVertices = item.Value;
4668
                            }
4669
                            else if (slope == SlopeType.HORIZONTAL &&
4670
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4671
                            {
4672
                                targetConnector = item.Key;
4673
                                length = distance;
4674
                                resultPoint = crossingPoint;
4675
                                targetVertices = item.Value;
4676
                            }
4677
                            else if (slope == SlopeType.VERTICAL &&
4678
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4679
                            {
4680
                                targetConnector = item.Key;
4681
                                length = distance;
4682
                                resultPoint = crossingPoint;
4683
                                targetVertices = item.Value;
4684
                            }
4685
                        }
4686
                    }
4687
                }
4688
            }
4689

    
4690
            foreach (var item in vertices)
4691
                if (item.Key != null && item.Key != targetConnector)
4692
                    ReleaseCOMObjects(item.Key);
4693

    
4694
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4695
            {
4696
                double tempResultX = resultPoint[0];
4697
                double tempResultY = resultPoint[1];
4698
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4699

    
4700
                GridSetting gridSetting = GridSetting.GetInstance();
4701

    
4702
                for (int i = 0; i < targetVertices.Count; i++)
4703
                {
4704
                    double[] point = targetVertices[i];
4705
                    double tempX = targetVertices[i][0];
4706
                    double tempY = targetVertices[i][1];
4707
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4708
                    if (tempX == tempResultX && tempY == tempResultY)
4709
                    {
4710
                        if (i == 0)
4711
                        {
4712
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4713
                            bool containZeroLength = false;
4714
                            if (connSymbol != null)
4715
                            {
4716
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4717
                                {
4718
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4719
                                        containZeroLength = true;
4720
                                }
4721
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4722
                                {
4723
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4724
                                        containZeroLength = true;
4725
                                }
4726
                            }
4727

    
4728
                            if (connSymbol == null ||
4729
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4730
                                containZeroLength)
4731
                            {
4732
                                bool bCalcX = false;
4733
                                bool bCalcY = false;
4734
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4735
                                    bCalcX = true;
4736
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4737
                                    bCalcY = true;
4738
                                else
4739
                                {
4740
                                    bCalcX = true;
4741
                                    bCalcY = true;
4742
                                }
4743

    
4744
                                if (bCalcX)
4745
                                {
4746
                                    double nextX = targetVertices[i + 1][0];
4747
                                    double newX = 0;
4748
                                    if (nextX > tempX)
4749
                                    {
4750
                                        newX = tempX + gridSetting.Length;
4751
                                        if (newX > nextX)
4752
                                            newX = (point[0] + nextX) / 2;
4753
                                    }
4754
                                    else
4755
                                    {
4756
                                        newX = tempX - gridSetting.Length;
4757
                                        if (newX < nextX)
4758
                                            newX = (point[0] + nextX) / 2;
4759
                                    }
4760
                                    resultPoint = new double[] { newX, resultPoint[1] };
4761
                                }
4762

    
4763
                                if (bCalcY)
4764
                                {
4765
                                    double nextY = targetVertices[i + 1][1];
4766
                                    double newY = 0;
4767
                                    if (nextY > tempY)
4768
                                    {
4769
                                        newY = tempY + gridSetting.Length;
4770
                                        if (newY > nextY)
4771
                                            newY = (point[1] + nextY) / 2;
4772
                                    }
4773
                                    else
4774
                                    {
4775
                                        newY = tempY - gridSetting.Length;
4776
                                        if (newY < nextY)
4777
                                            newY = (point[1] + nextY) / 2;
4778
                                    }
4779
                                    resultPoint = new double[] { resultPoint[0], newY };
4780
                                }
4781
                            }
4782
                        }
4783
                        else if (i == targetVertices.Count - 1)
4784
                        {
4785
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4786
                            bool containZeroLength = false;
4787
                            if (connSymbol != null)
4788
                            {
4789
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4790
                                {
4791
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4792
                                        containZeroLength = true;
4793
                                }
4794
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4795
                                {
4796
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4797
                                        containZeroLength = true;
4798
                                }
4799
                            }
4800

    
4801
                            if (connSymbol == null ||
4802
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4803
                                containZeroLength)
4804
                            {
4805
                                bool bCalcX = false;
4806
                                bool bCalcY = false;
4807
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4808
                                    bCalcX = true;
4809
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4810
                                    bCalcY = true;
4811
                                else
4812
                                {
4813
                                    bCalcX = true;
4814
                                    bCalcY = true;
4815
                                }
4816

    
4817
                                if (bCalcX)
4818
                                {
4819
                                    double nextX = targetVertices[i - 1][0];
4820
                                    double newX = 0;
4821
                                    if (nextX > tempX)
4822
                                    {
4823
                                        newX = tempX + gridSetting.Length;
4824
                                        if (newX > nextX)
4825
                                            newX = (point[0] + nextX) / 2;
4826
                                    }
4827
                                    else
4828
                                    {
4829
                                        newX = tempX - gridSetting.Length;
4830
                                        if (newX < nextX)
4831
                                            newX = (point[0] + nextX) / 2;
4832
                                    }
4833
                                    resultPoint = new double[] { newX, resultPoint[1] };
4834
                                }
4835

    
4836
                                if (bCalcY)
4837
                                {
4838
                                    double nextY = targetVertices[i - 1][1];
4839
                                    double newY = 0;
4840
                                    if (nextY > tempY)
4841
                                    {
4842
                                        newY = tempY + gridSetting.Length;
4843
                                        if (newY > nextY)
4844
                                            newY = (point[1] + nextY) / 2;
4845
                                    }
4846
                                    else
4847
                                    {
4848
                                        newY = tempY - gridSetting.Length;
4849
                                        if (newY < nextY)
4850
                                            newY = (point[1] + nextY) / 2;
4851
                                    }
4852
                                    resultPoint = new double[] { resultPoint[0], newY };
4853
                                }
4854
                            }
4855
                        }
4856
                        break;
4857
                    }
4858
                }
4859
            }
4860

    
4861
            x = resultPoint[0];
4862
            y = resultPoint[1];
4863

    
4864
            return targetConnector;
4865
        }
4866

    
4867
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4868
        {
4869
            LMConnector result = null;
4870
            List<LMConnector> connectors = new List<LMConnector>();
4871
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4872

    
4873
            if (modelItem != null)
4874
            {
4875
                foreach (LMRepresentation rep in modelItem.Representations)
4876
                {
4877
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4878
                        connectors.Add(dataSource.GetConnector(rep.Id));
4879
                }
4880

    
4881
                ReleaseCOMObjects(modelItem);
4882
            }
4883

    
4884
            if (connectors.Count == 1)
4885
                result = connectors[0];
4886
            else
4887
                foreach (var item in connectors)
4888
                    ReleaseCOMObjects(item);
4889

    
4890
            return result;
4891
        }
4892

    
4893
        private LMConnector GetLMConnectorFirst(string modelItemID)
4894
        {
4895
            LMConnector result = null;
4896
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4897

    
4898
            if (modelItem != null)
4899
            {
4900
                foreach (LMRepresentation rep in modelItem.Representations)
4901
                {
4902
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" &&
4903
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4904
                    {
4905
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4906
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4907
                        {
4908
                            result = connector;
4909
                            break;
4910
                        }
4911
                        else
4912
                        {
4913
                            ReleaseCOMObjects(connector);
4914
                            connector = null;
4915
                        }
4916
                    }
4917
                }
4918
                ReleaseCOMObjects(modelItem);
4919
                modelItem = null;
4920
            }
4921

    
4922
            return result;
4923
        }
4924

    
4925
        private int GetConnectorCount(string modelItemID)
4926
        {
4927
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4928
            int result = 0;
4929
            if (modelItem != null)
4930
            {
4931
                foreach (LMRepresentation rep in modelItem.Representations)
4932
                {
4933
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4934
                        result++;
4935
                    ReleaseCOMObjects(rep);
4936
                }
4937
                ReleaseCOMObjects(modelItem);
4938
            }
4939

    
4940
            return result;
4941
        }
4942

    
4943
        public List<string> GetRepresentations(string modelItemID)
4944
        {
4945
            List<string> result = new List<string>(); ;
4946
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4947
            if (modelItem != null)
4948
            {
4949
                foreach (LMRepresentation rep in modelItem.Representations)
4950
                {
4951
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4952
                        result.Add(rep.Id);
4953
                }
4954
                ReleaseCOMObjects(modelItem);
4955
            }
4956

    
4957
            return result;
4958
        }
4959

    
4960
        private void LineNumberModeling(LineNumber lineNumber)
4961
        {
4962
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4963
            if (line != null)
4964
            {
4965
                double x = 0;
4966
                double y = 0;
4967
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4968

    
4969
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4970
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4971
                if (connectedLMConnector != null)
4972
                {
4973
                    Array points = new double[] { 0, x, y };
4974
                    lineNumber.SPPID.SPPID_X = x;
4975
                    lineNumber.SPPID.SPPID_Y = y;
4976
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4977

    
4978
                    if (_LmLabelPresist != null)
4979
                    {
4980
                        _LmLabelPresist.Commit();
4981
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4982
                        ReleaseCOMObjects(_LmLabelPresist);
4983
                    }
4984
                }
4985

    
4986
                foreach (var item in connectorVertices)
4987
                    ReleaseCOMObjects(item.Key);
4988
            }
4989
        }
4990
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4991
        {
4992
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4993
            if (line == null || line.SPPID.Vertices == null)
4994
                return;
4995

    
4996
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4997
            {
4998
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4999
                if (removeLabel != null)
5000
                {
5001
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
5002
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
5003

    
5004
                    GridSetting gridSetting = GridSetting.GetInstance();
5005
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
5006

    
5007
                    double[] labelRange = null;
5008
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
5009
                    List<double[]> vertices = GetConnectorVertices(connector);
5010

    
5011
                    double[] resultStart = null;
5012
                    double[] resultEnd = null;
5013
                    double distance = double.MaxValue;
5014
                    for (int i = 0; i < vertices.Count - 1; i++)
5015
                    {
5016
                        double[] startPoint = vertices[i];
5017
                        double[] endPoint = vertices[i + 1];
5018
                        foreach (var item in line.SPPID.Vertices)
5019
                        {
5020
                            double[] lineStartPoint = item[0];
5021
                            double[] lineEndPoint = item[item.Count - 1];
5022

    
5023
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
5024
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
5025
                            if (tempDistance < distance)
5026
                            {
5027
                                distance = tempDistance;
5028
                                resultStart = startPoint;
5029
                                resultEnd = endPoint;
5030
                            }
5031
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
5032
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
5033
                            if (tempDistance < distance)
5034
                            {
5035
                                distance = tempDistance;
5036
                                resultStart = startPoint;
5037
                                resultEnd = endPoint;
5038
                            }
5039
                        }
5040
                    }
5041

    
5042
                    if (resultStart != null && resultEnd != null)
5043
                    {
5044
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
5045
                        double lineStartX = 0;
5046
                        double lineStartY = 0;
5047
                        double lineEndX = 0;
5048
                        double lineEndY = 0;
5049
                        double lineNumberX = 0;
5050
                        double lineNumberY = 0;
5051
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
5052
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
5053

    
5054
                        double lineX = (lineStartX + lineEndX) / 2;
5055
                        double lineY = (lineStartY + lineEndY) / 2;
5056
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
5057
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
5058

    
5059
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
5060
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
5061
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
5062
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
5063

    
5064
                        double offsetX = 0;
5065
                        double offsetY = 0;
5066
                        if (slope == SlopeType.HORIZONTAL)
5067
                        {
5068
                            // Line Number 아래
5069
                            if (lineY < lineNumberY)
5070
                            {
5071
                                offsetX = labelCenterX - SPPIDCenterX;
5072
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
5073
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5074
                            }
5075
                            // Line Number 위
5076
                            else
5077
                            {
5078
                                offsetX = labelCenterX - SPPIDCenterX;
5079
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
5080
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5081
                            }
5082
                        }
5083
                        else if (slope == SlopeType.VERTICAL)
5084
                        {
5085
                            // Line Number 오르쪽
5086
                            if (lineX < lineNumberX)
5087
                            {
5088
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
5089
                                offsetY = labelCenterY - SPPIDCenterY;
5090
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5091
                            }
5092
                            // Line Number 왼쪽
5093
                            else
5094
                            {
5095
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
5096
                                offsetY = labelCenterY - SPPIDCenterY;
5097
                                MoveLineNumber(lineNumber, offsetX, offsetY);
5098
                            }
5099
                        }
5100

    
5101
                        if (offsetY != 0 || offsetY != 0)
5102
                        {
5103
                            if (connector.ConnectItem1SymbolObject != null &&
5104
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
5105
                            {
5106
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
5107

    
5108
                                double x1, y1, x2, y2, originX, originY;
5109
                                symbol.Range(out x1, out y1, out x2, out y2);
5110
                                symbol.GetOrigin(out originX, out originY);
5111
                                if (originX < lineNumber.SPPID.SPPID_X)
5112
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5113
                                else
5114
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5115
                            }
5116
                            else if (connector.ConnectItem2SymbolObject != null &&
5117
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
5118
                            {
5119
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
5120

    
5121
                                double x1, y1, x2, y2, originX, originY;
5122
                                symbol.Range(out x1, out y1, out x2, out y2);
5123
                                symbol.GetOrigin(out originX, out originY);
5124
                                if (originX < lineNumber.SPPID.SPPID_X)
5125
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
5126
                                else
5127
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
5128
                            }
5129

    
5130
                            radApp.ActiveSelectSet.RemoveAll();
5131
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
5132
                            if (dependency != null)
5133
                            {
5134
                                radApp.ActiveSelectSet.Add(dependency);
5135
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
5136
                                transform.DefineByMove2d(-offsetX, -offsetY);
5137
                                radApp.ActiveSelectSet.Transform(transform, true);
5138
                                radApp.ActiveSelectSet.RemoveAll();
5139
                            }
5140
                        }
5141

    
5142
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
5143
                        {
5144
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
5145
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
5146
                        }
5147
                    }
5148

    
5149

    
5150
                    ReleaseCOMObjects(connector);
5151
                    connector = null;
5152
                }
5153

    
5154
                ReleaseCOMObjects(removeLabel);
5155
                removeLabel = null;
5156
            }
5157
        }
5158
        /// <summary>
5159
        /// Flow Mark Modeling
5160
        /// </summary>
5161
        /// <param name="line"></param>
5162
        private void FlowMarkModeling(Line line)
5163
        {
5164
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
5165
            {
5166
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
5167
                if (connector != null)
5168
                {
5169
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
5170
                    List<double[]> vertices = GetConnectorVertices(connector);
5171
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
5172
                    double[] point = vertices[vertices.Count - 1];
5173
                    Array array = new double[] { 0, point[0], point[1] };
5174
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, null, null, LabeledItem: connector.AsLMRepresentation());
5175
                    if (_LMLabelPersist != null)
5176
                    {
5177
                        _LMLabelPersist.Commit();
5178
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
5179
                        ReleaseCOMObjects(_LMLabelPersist);
5180
                    }
5181
                }
5182
            }
5183
        }
5184

    
5185
        /// <summary>
5186
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
5187
        /// </summary>
5188
        /// <param name="lineNumber"></param>
5189
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
5190
        {
5191
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
5192
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
5193
            {
5194
                if (a.ATTRIBUTE == "Tag Seq No")
5195
                    return 1;
5196
                else if (b.ATTRIBUTE == "Tag Seq No")
5197
                    return -1;
5198

    
5199
                return 0;
5200
            }
5201

    
5202
            foreach (LineRun run in lineNumber.RUNS)
5203
            {
5204
                foreach (var item in run.RUNITEMS)
5205
                {
5206
                    if (item.GetType() == typeof(Line))
5207
                    {
5208
                        Line line = item as Line;
5209
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
5210
                        {
5211
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5212
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5213
                            {
5214
                                foreach (var attribute in lineNumber.ATTRIBUTES)
5215
                                {
5216
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
5217
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5218
                                    {
5219
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5220
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
5221
                                        {
5222
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5223
                                            if (_FluidSystemAttribute != null)
5224
                                            {
5225
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
5226
                                                if (dt.Rows.Count == 1)
5227
                                                {
5228
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5229
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5230
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5231
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5232
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
5233

    
5234
                                                    if (_LMAAttribute != null)
5235
                                                    {
5236
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5237
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5238
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
5239
                                                            _LMAAttribute.set_Value(attribute.VALUE);
5240
                                                    }
5241
                                                }
5242
                                                if (dt != null)
5243
                                                    dt.Dispose();
5244
                                            }
5245
                                        }
5246
                                        else if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(attribute.VALUE) && _LMAAttribute != null)
5247
                                        {
5248
                                            DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", attribute.VALUE));
5249

    
5250
                                            if (rows.Length.Equals(1))
5251
                                            {
5252
                                                if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5253
                                                    attribute.VALUE = rows[0]["MetricStr"].ToString();
5254
                                                else
5255
                                                    attribute.VALUE = rows[0]["InchStr"].ToString();
5256

    
5257
                                                if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5258
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5259
                                                else if (_LMAAttribute.get_Value() != attribute.VALUE)
5260
                                                    _LMAAttribute.set_Value(attribute.VALUE);
5261
                                            }
5262
                                        }
5263
                                        else if (_LMAAttribute != null)
5264
                                        {
5265
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5266
                                                _LMAAttribute.set_Value(attribute.VALUE);
5267
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
5268
                                                _LMAAttribute.set_Value(attribute.VALUE);
5269
                                        }
5270
                                    }
5271
                                }
5272
                                _LMModelItem.Commit();
5273
                            }
5274
                            if (_LMModelItem != null)
5275
                                ReleaseCOMObjects(_LMModelItem);
5276
                            endLine.Add(line.SPPID.ModelItemId);
5277
                        }
5278
                    }
5279
                }
5280
            }
5281
        }
5282

    
5283
        /// <summary>
5284
        /// Symbol Attribute 입력 메서드
5285
        /// </summary>
5286
        /// <param name="item"></param>
5287
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
5288
        {
5289
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
5290
            string sRep = null;
5291
            string sModelID = null;
5292
            if (targetItem.GetType() == typeof(Symbol))
5293
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
5294
            else if (targetItem.GetType() == typeof(Equipment))
5295
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
5296
            else if (targetItem.GetType() == typeof(Line))
5297
                sModelID = ((Line)targetItem).SPPID.ModelItemId;
5298

    
5299
            if (!string.IsNullOrEmpty(sRep))
5300
            {
5301
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
5302
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
5303
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5304

    
5305
                foreach (var item in targetAttributes)
5306
                {
5307
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5308
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5309
                    {
5310
                        if (!mapping.IsText)
5311
                        {
5312
                            LMAAttribute _LMAAttribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5313
                            if (mapping.SPPIDATTRIBUTENAME.Equals("NominalDiameter") && !string.IsNullOrEmpty(item.VALUE) && _LMAAttribute != null)
5314
                            {
5315
                                DataRow[] rows = nominalDiameterTable.Select(string.Format("MetricStr = '{0}' OR InchStr = '{0}'", item.VALUE));
5316

    
5317
                                if (rows.Length.Equals(1))
5318
                                {
5319
                                    if (_ETCSetting.UnitSetting != null && _ETCSetting.UnitSetting.Equals("Metric"))
5320
                                        item.VALUE = rows[0]["MetricStr"].ToString();
5321
                                    else
5322
                                        item.VALUE = rows[0]["InchStr"].ToString();
5323

    
5324
                                    if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5325
                                        _LMAAttribute.set_Value(item.VALUE);
5326
                                    else if (_LMAAttribute.get_Value() != item.VALUE)
5327
                                        _LMAAttribute.set_Value(item.VALUE);
5328
                                }
5329
                            }
5330
                            else if (_LMAAttribute != null)
5331
                            {
5332
                                _LMAAttribute.set_Value(item.VALUE);
5333
                                // OPC 일경우 Attribute 저장
5334
                                if (targetItem.GetType() == typeof(Symbol))
5335
                                {
5336
                                    Symbol symbol = targetItem as Symbol;
5337
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
5338
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
5339
                                }
5340
                            }
5341
                        }
5342
                        else
5343
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
5344
                    }
5345
                }
5346
                _LMModelItem.Commit();
5347

    
5348
                ReleaseCOMObjects(_Attributes);
5349
                ReleaseCOMObjects(_LMModelItem);
5350
                ReleaseCOMObjects(_LMSymbol);
5351
            }
5352
            else if (!string.IsNullOrEmpty(sModelID))
5353
            {
5354
                LMModelItem _LMModelItem = dataSource.GetModelItem(sModelID);
5355
                LMAAttributes _Attributes = _LMModelItem.Attributes;
5356

    
5357
                foreach (var item in targetAttributes)
5358
                {
5359
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
5360
                    if (mapping == null)
5361
                        continue;
5362
                    
5363
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
5364
                    if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(item.VALUE))
5365
                    {
5366
                        LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
5367
                        if (_FluidSystemAttribute != null)
5368
                        {
5369
                            DataTable dt = SPPID_DB.GetFluidSystemInfo(item.VALUE);
5370
                            if (dt.Rows.Count == 1)
5371
                            {
5372
                                string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
5373
                                if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
5374
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5375
                                else if (_FluidSystemAttribute.get_Value() != fluidSystem)
5376
                                    _FluidSystemAttribute.set_Value(fluidSystem);
5377

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

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

    
5401
                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5402
                                _LMAAttribute.set_Value(item.VALUE);
5403
                            else if (_LMAAttribute.get_Value() != item.VALUE)
5404
                                _LMAAttribute.set_Value(item.VALUE);
5405
                        }
5406
                    }
5407
                    else if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
5408
                    {
5409
                        if (!mapping.IsText)
5410
                        {
5411
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
5412
                            if (_Attribute != null)
5413
                                _Attribute.set_Value(item.VALUE);
5414
                        }
5415
                    }
5416
                }
5417
                _LMModelItem.Commit();
5418

    
5419
                ReleaseCOMObjects(_Attributes);
5420
                ReleaseCOMObjects(_LMModelItem);
5421
            }
5422
        }
5423

    
5424
        /// <summary>
5425
        /// Input SpecBreak Attribute
5426
        /// </summary>
5427
        /// <param name="specBreak"></param>
5428
        private void InputSpecBreakAttribute(SpecBreak specBreak)
5429
        {
5430
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
5431
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
5432

    
5433
            if (upStreamObj != null &&
5434
                downStreamObj != null)
5435
            {
5436
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
5437

    
5438
                if (targetLMConnector != null)
5439
                {
5440
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
5441
                    {
5442
                        string symbolPath = _LMLabelPersist.get_FileName();
5443
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
5444
                        if (mapping != null)
5445
                        {
5446
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
5447
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5448
                            {
5449
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
5450
                                if (values.Length == 2)
5451
                                {
5452
                                    string upStreamValue = values[0];
5453
                                    string downStreamValue = values[1];
5454

    
5455
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
5456
                                }
5457
                            }
5458
                        }
5459
                    }
5460

    
5461
                    ReleaseCOMObjects(targetLMConnector);
5462
                }
5463
            }
5464

    
5465

    
5466
            #region 내부에서만 쓰는 메서드
5467
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
5468
            {
5469
                Symbol upStreamSymbol = _upStreamObj as Symbol;
5470
                Line upStreamLine = _upStreamObj as Line;
5471
                Symbol downStreamSymbol = _downStreamObj as Symbol;
5472
                Line downStreamLine = _downStreamObj as Line;
5473
                // 둘다 Line일 경우
5474
                if (upStreamLine != null && downStreamLine != null)
5475
                {
5476
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5477
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5478
                }
5479
                // 둘다 Symbol일 경우
5480
                else if (upStreamSymbol != null && downStreamSymbol != null)
5481
                {
5482
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
5483
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5484
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5485

    
5486
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5487
                    {
5488
                        if (connector.get_ItemStatus() != "Active")
5489
                            continue;
5490

    
5491
                        if (connector.Id != zeroLenthConnector.Id)
5492
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5493
                    }
5494

    
5495
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5496
                    {
5497
                        if (connector.get_ItemStatus() != "Active")
5498
                            continue;
5499

    
5500
                        if (connector.Id != zeroLenthConnector.Id)
5501
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5502
                    }
5503

    
5504
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5505
                    {
5506
                        if (connector.get_ItemStatus() != "Active")
5507
                            continue;
5508

    
5509
                        if (connector.Id != zeroLenthConnector.Id)
5510
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5511
                    }
5512

    
5513
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5514
                    {
5515
                        if (connector.get_ItemStatus() != "Active")
5516
                            continue;
5517

    
5518
                        if (connector.Id != zeroLenthConnector.Id)
5519
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5520
                    }
5521

    
5522
                    ReleaseCOMObjects(zeroLenthConnector);
5523
                    ReleaseCOMObjects(upStreamLMSymbol);
5524
                    ReleaseCOMObjects(downStreamLMSymbol);
5525
                }
5526
                else if (upStreamSymbol != null && downStreamLine != null)
5527
                {
5528
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
5529
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
5530
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
5531

    
5532
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
5533
                    {
5534
                        if (connector.get_ItemStatus() != "Active")
5535
                            continue;
5536

    
5537
                        if (connector.Id == zeroLenthConnector.Id)
5538
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5539
                    }
5540

    
5541
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
5542
                    {
5543
                        if (connector.get_ItemStatus() != "Active")
5544
                            continue;
5545

    
5546
                        if (connector.Id == zeroLenthConnector.Id)
5547
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
5548
                    }
5549

    
5550
                    ReleaseCOMObjects(zeroLenthConnector);
5551
                    ReleaseCOMObjects(upStreamLMSymbol);
5552
                }
5553
                else if (upStreamLine != null && downStreamSymbol != null)
5554
                {
5555
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
5556
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
5557
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
5558

    
5559
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
5560
                    {
5561
                        if (connector.get_ItemStatus() != "Active")
5562
                            continue;
5563

    
5564
                        if (connector.Id == zeroLenthConnector.Id)
5565
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5566
                    }
5567

    
5568
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
5569
                    {
5570
                        if (connector.get_ItemStatus() != "Active")
5571
                            continue;
5572

    
5573
                        if (connector.Id == zeroLenthConnector.Id)
5574
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
5575
                    }
5576

    
5577
                    ReleaseCOMObjects(zeroLenthConnector);
5578
                    ReleaseCOMObjects(downStreamLMSymbol);
5579
                }
5580
            }
5581

    
5582
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
5583
            {
5584
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
5585
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5586
                {
5587
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5588
                    if (_LMAAttribute != null)
5589
                    {
5590
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5591
                            _LMAAttribute.set_Value(value);
5592
                        else if (_LMAAttribute.get_Value() != value)
5593
                            _LMAAttribute.set_Value(value);
5594
                    }
5595

    
5596
                    _LMModelItem.Commit();
5597
                }
5598
                if (_LMModelItem != null)
5599
                    ReleaseCOMObjects(_LMModelItem);
5600
            }
5601

    
5602
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
5603
            {
5604
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
5605
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
5606
                {
5607
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
5608
                    if (_LMAAttribute != null)
5609
                    {
5610
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
5611
                            _LMAAttribute.set_Value(value);
5612
                        else if (_LMAAttribute.get_Value() != value)
5613
                            _LMAAttribute.set_Value(value);
5614
                    }
5615

    
5616
                    _LMModelItem.Commit();
5617
                }
5618
                if (_LMModelItem != null)
5619
                    ReleaseCOMObjects(_LMModelItem);
5620
            }
5621
            #endregion
5622
        }
5623

    
5624
        private void InputEndBreakAttribute(EndBreak endBreak)
5625
        {
5626
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
5627
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
5628

    
5629
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
5630
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
5631
            {
5632
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
5633
                if (labelPersist != null)
5634
                {
5635
                    LMRepresentation representation = labelPersist.RepresentationObject;
5636
                    if (representation != null)
5637
                    {
5638
                        LMConnector connector = dataSource.GetConnector(representation.Id);
5639
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
5640
                        string modelItemID = connector.ModelItemID;
5641
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
5642
                        {
5643
                            List<string> modelItemIDs = new List<string>();
5644
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5645
                            {
5646
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
5647
                                foreach (LMConnector item in symbol.Connect1Connectors)
5648
                                {
5649
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5650
                                        modelItemIDs.Add(item.ModelItemID);
5651
                                    ReleaseCOMObjects(item);
5652
                                }
5653
                                foreach (LMConnector item in symbol.Connect2Connectors)
5654
                                {
5655
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5656
                                        modelItemIDs.Add(item.ModelItemID);
5657
                                    ReleaseCOMObjects(item);
5658
                                }
5659
                                ReleaseCOMObjects(symbol);
5660
                                symbol = null;
5661
                            }
5662
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5663
                            {
5664
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
5665
                                foreach (LMConnector item in symbol.Connect1Connectors)
5666
                                {
5667
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5668
                                        modelItemIDs.Add(item.ModelItemID);
5669
                                    ReleaseCOMObjects(item);
5670
                                }
5671
                                foreach (LMConnector item in symbol.Connect2Connectors)
5672
                                {
5673
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
5674
                                        modelItemIDs.Add(item.ModelItemID);
5675
                                    ReleaseCOMObjects(item);
5676
                                }
5677
                                ReleaseCOMObjects(symbol);
5678
                                symbol = null;
5679
                            }
5680

    
5681
                            modelItemIDs = modelItemIDs.Distinct().ToList();
5682
                            if (modelItemIDs.Count == 1)
5683
                            {
5684
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
5685
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
5686
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
5687
                                {
5688
                                    bool result = false;
5689
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
5690
                                    {
5691
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
5692
                                            result = true;
5693
                                        ReleaseCOMObjects(loop);
5694
                                    }
5695

    
5696
                                    if (result)
5697
                                    {
5698
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5699
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5700
                                        //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5701
                                        //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5702
                                        ZeroLengthModelItem.Commit();
5703
                                    }
5704
                                    else
5705
                                    {
5706
                                        List<string> loopModelItems = new List<string>();
5707
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
5708
                                        {
5709
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
5710
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5711
                                            {
5712
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5713
                                                    loopModelItems.Add(loop.ModelItemID);
5714
                                                ReleaseCOMObjects(loop);
5715
                                            }
5716
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5717
                                            {
5718
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5719
                                                    loopModelItems.Add(loop.ModelItemID);
5720
                                                ReleaseCOMObjects(loop);
5721
                                            }
5722
                                            ReleaseCOMObjects(_symbol);
5723
                                            _symbol = null;
5724
                                        }
5725
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5726
                                        {
5727
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5728
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5729
                                            {
5730
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5731
                                                    loopModelItems.Add(loop.ModelItemID);
5732
                                                ReleaseCOMObjects(loop);
5733
                                            }
5734
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5735
                                            {
5736
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5737
                                                    loopModelItems.Add(loop.ModelItemID);
5738
                                                ReleaseCOMObjects(loop);
5739
                                            }
5740
                                            ReleaseCOMObjects(_symbol);
5741
                                            _symbol = null;
5742
                                        }
5743

    
5744
                                        loopModelItems = loopModelItems.Distinct().ToList();
5745
                                        if (loopModelItems.Count == 1)
5746
                                        {
5747
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5748
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5749
                                            //object value2 = loopModelItem.Attributes["SubUnitNumber"].get_Value();
5750
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5751
                                            //modelItem.Attributes["SubUnitNumber"].set_Value(value2);
5752
                                            modelItem.Commit();
5753
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5754
                                            //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5755
                                            ZeroLengthModelItem.Commit();
5756

    
5757
                                            ReleaseCOMObjects(loopModelItem);
5758
                                            loopModelItem = null;
5759
                                        }
5760
                                    }
5761
                                }
5762
                                else
5763
                                {
5764
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5765
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5766
                                    //object value2 = modelItem.Attributes["SubUnitNumber"].get_Value();
5767
                                    //ZeroLengthModelItem.Attributes["SubUnitNumber"].set_Value(value2);
5768
                                    ZeroLengthModelItem.Commit();
5769
                                }
5770
                                ReleaseCOMObjects(modelItem);
5771
                                modelItem = null;
5772
                                ReleaseCOMObjects(onlyOne);
5773
                                onlyOne = null;
5774
                            }
5775
                        }
5776
                        ReleaseCOMObjects(connector);
5777
                        connector = null;
5778
                        ReleaseCOMObjects(ZeroLengthModelItem);
5779
                        ZeroLengthModelItem = null;
5780
                    }
5781
                    ReleaseCOMObjects(representation);
5782
                    representation = null;
5783
                }
5784
                ReleaseCOMObjects(labelPersist);
5785
                labelPersist = null;
5786
            }
5787
        }
5788

    
5789
        /// <summary>
5790
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5791
        /// </summary>
5792
        /// <param name="text"></param>
5793
        private void NormalTextModeling(Text text)
5794
        {
5795
            LMSymbol _LMSymbol = null;
5796

    
5797
            LMItemNote _LMItemNote = null;
5798
            LMAAttribute _LMAAttribute = null;
5799

    
5800
            double x = 0;
5801
            double y = 0;
5802
            double angle = text.ANGLE;
5803
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5804

    
5805
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5806
            text.SPPID.SPPID_X = x;
5807
            text.SPPID.SPPID_Y = y;
5808

    
5809
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5810
            if (_LMSymbol != null)
5811
            {
5812
                _LMSymbol.Commit();
5813
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5814
                if (_LMItemNote != null)
5815
                {
5816
                    _LMItemNote.Commit();
5817
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5818
                    if (_LMAAttribute != null)
5819
                    {
5820
                        _LMAAttribute.set_Value(text.VALUE);
5821
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5822
                        _LMItemNote.Commit();
5823

    
5824

    
5825
                        double[] range = null;
5826
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5827
                        {
5828
                            double[] temp = null;
5829
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5830
                            if (temp != null)
5831
                            {
5832
                                if (range == null)
5833
                                    range = temp;
5834
                                else
5835
                                {
5836
                                    range = new double[] {
5837
                                            Math.Min(range[0], temp[0]),
5838
                                            Math.Min(range[1], temp[1]),
5839
                                            Math.Max(range[2], temp[2]),
5840
                                            Math.Max(range[3], temp[3])
5841
                                        };
5842
                                }
5843
                            }
5844
                        }
5845
                        text.SPPID.Range = range;
5846

    
5847
                        if (_LMAAttribute != null)
5848
                            ReleaseCOMObjects(_LMAAttribute);
5849
                        if (_LMItemNote != null)
5850
                            ReleaseCOMObjects(_LMItemNote);
5851
                    }
5852

    
5853
                    TextCorrectModeling(text);
5854
                }
5855
            }
5856
            if (_LMSymbol != null)
5857
                ReleaseCOMObjects(_LMSymbol);
5858
        }
5859

    
5860
        private void DefaultTextModeling(string value, double x, double y)
5861
        {
5862
            LMSymbol _LMSymbol = null;
5863

    
5864
            LMItemNote _LMItemNote = null;
5865
            LMAAttribute _LMAAttribute = null;
5866

    
5867
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5868
            if (_LMSymbol != null)
5869
            {
5870
                _LMSymbol.Commit();
5871
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5872
                if (_LMItemNote != null)
5873
                {
5874
                    _LMItemNote.Commit();
5875
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5876
                    if (_LMAAttribute != null)
5877
                    {
5878
                        _LMAAttribute.set_Value(value);
5879
                        _LMItemNote.Commit();
5880

    
5881
                        if (_LMAAttribute != null)
5882
                            ReleaseCOMObjects(_LMAAttribute);
5883
                        if (_LMItemNote != null)
5884
                            ReleaseCOMObjects(_LMItemNote);
5885
                    }
5886
                }
5887
            }
5888
            if (_LMSymbol != null)
5889
                ReleaseCOMObjects(_LMSymbol);
5890
        }
5891

    
5892
        private void AssociationTextModeling(Text text)
5893
        {
5894
            LMSymbol _LMSymbol = null;
5895
            LMConnector connectedLMConnector = null;
5896
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5897
            if (owner != null && (owner.GetType() == typeof(Symbol) || owner.GetType() == typeof(Equipment)))
5898
            {
5899
                Symbol symbol = owner as Symbol;
5900
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5901
                if (_LMSymbol != null)
5902
                {
5903
                    foreach (BaseModel.Attribute attribute in symbol.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5904
                    {
5905
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5906
                        {
5907
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5908

    
5909
                            if (mapping != null)
5910
                            {
5911
                                double x = 0;
5912
                                double y = 0;
5913

    
5914
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5915
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5916
                                Array array = new double[] { 0, x, y };
5917
                                text.SPPID.SPPID_X = x;
5918
                                text.SPPID.SPPID_Y = y;
5919
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5920
                                if (_LMLabelPersist != null)
5921
                                {
5922
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5923
                                    _LMLabelPersist.Commit();
5924
                                    ReleaseCOMObjects(_LMLabelPersist);
5925
                                }
5926
                            }
5927
                        }
5928
                    }
5929
                }
5930
            }
5931
            else if (owner != null && owner.GetType() == typeof(Line))
5932
            {
5933
                Line line = owner as Line;
5934
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5935
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5936

    
5937
                if (connectedLMConnector != null)
5938
                {
5939
                    foreach (BaseModel.Attribute attribute in line.ATTRIBUTES.FindAll(x => x.ASSOCITEM == text.UID))
5940
                    {
5941
                        if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5942
                        {
5943
                            AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5944

    
5945
                            if (mapping != null)
5946
                            {
5947
                                double x = 0;
5948
                                double y = 0;
5949
                                CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5950
                                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5951
                                Array array = new double[] { 0, x, y };
5952

    
5953
                                LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5954
                                if (_LMLabelPersist != null)
5955
                                {
5956
                                    text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5957
                                    _LMLabelPersist.Commit();
5958

    
5959
                                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5960
                                    if (dependency != null)
5961
                                    {
5962
                                        radApp.ActiveSelectSet.RemoveAll();
5963
                                        radApp.ActiveSelectSet.Add(dependency);
5964
                                        Ingr.RAD2D.Transform transform = dependency.GetTransform();
5965
                                        transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5966
                                        radApp.ActiveSelectSet.Transform(transform, true);
5967
                                        radApp.ActiveSelectSet.RemoveAll();
5968
                                    }
5969

    
5970
                                    ReleaseCOMObjects(_LMLabelPersist);
5971
                                }
5972
                            }
5973
                        }
5974
                    }
5975
                }
5976
            }
5977
            if (_LMSymbol != null)
5978
                ReleaseCOMObjects(_LMSymbol);
5979
        }
5980

    
5981
        private void TextCorrectModeling(Text text)
5982
        {
5983
            if (text.SPPID.Range == null)
5984
                return;
5985

    
5986
            bool needRemodeling = false;
5987
            bool loop = true;
5988
            GridSetting gridSetting = GridSetting.GetInstance();
5989
            while (loop)
5990
            {
5991
                loop = false;
5992
                foreach (var overlapText in document.TEXTINFOS)
5993
                {
5994
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5995
                        continue;
5996

    
5997
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5998
                    {
5999
                        double percentX = 0;
6000
                        double percentY = 0;
6001
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
6002
                        {
6003
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
6004
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
6005
                        }
6006
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
6007
                        {
6008
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
6009
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
6010
                        }
6011

    
6012
                        double tempX = 0;
6013
                        double tempY = 0;
6014
                        bool overlapX = false;
6015
                        bool overlapY = false;
6016
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6017
                        if (percentX >= percentY)
6018
                        {
6019
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6020
                            double move = gridSetting.Length * count;
6021
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
6022
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
6023
                            needRemodeling = true;
6024
                            loop = true;
6025
                        }
6026
                        else
6027
                        {
6028
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6029
                            double move = gridSetting.Length * count;
6030
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
6031
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
6032
                            needRemodeling = true;
6033
                            loop = true;
6034
                        }
6035
                    }
6036
                }
6037
            }
6038

    
6039

    
6040
            if (needRemodeling)
6041
            {
6042
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
6043
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6044
                text.SPPID.RepresentationId = null;
6045

    
6046
                LMItemNote _LMItemNote = null;
6047
                LMAAttribute _LMAAttribute = null;
6048
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
6049
                if (_LMSymbol != null)
6050
                {
6051
                    _LMSymbol.Commit();
6052
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6053
                    if (_LMItemNote != null)
6054
                    {
6055
                        _LMItemNote.Commit();
6056
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6057
                        if (_LMAAttribute != null)
6058
                        {
6059
                            _LMAAttribute.set_Value(text.VALUE);
6060
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6061
                            _LMItemNote.Commit();
6062

    
6063
                            ReleaseCOMObjects(_LMAAttribute);
6064
                            ReleaseCOMObjects(_LMItemNote);
6065
                        }
6066
                    }
6067
                }
6068

    
6069
                ReleaseCOMObjects(symbol);
6070
                symbol = null;
6071
                ReleaseCOMObjects(_LMItemNote);
6072
                _LMItemNote = null;
6073
                ReleaseCOMObjects(_LMAAttribute);
6074
                _LMAAttribute = null;
6075
                ReleaseCOMObjects(_LMSymbol);
6076
                _LMSymbol = null;
6077
            }
6078
        }
6079

    
6080
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
6081
        {
6082
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
6083
            {
6084
                List<Text> allTexts = new List<Text>();
6085
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6086
                LMRepresentation representation = targetLabel.RepresentationObject;
6087
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
6088
                if (targetLabel.RepresentationObject != null && symbol != null)
6089
                {
6090
                    double[] symbolRange = null;
6091
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
6092
                    if (symbolRange != null)
6093
                    {
6094
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
6095
                        {
6096
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
6097
                            if (findText != null)
6098
                            {
6099
                                double[] range = null;
6100
                                GetSPPIDSymbolRange(labelPersist, ref range);
6101
                                findText.SPPID.Range = range;
6102
                                allTexts.Add(findText);
6103
                            }
6104

    
6105
                            ReleaseCOMObjects(labelPersist);
6106
                        }
6107

    
6108
                        if (allTexts.Count > 0)
6109
                        {
6110
                            #region Sort Text By Y
6111
                            allTexts.Sort(SortTextByY);
6112
                            int SortTextByY(Text a, Text b)
6113
                            {
6114
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
6115
                            }
6116
                            #endregion
6117

    
6118
                            #region 정렬하기전 방향
6119
                            List<Text> left = new List<Text>();
6120
                            List<Text> down = new List<Text>();
6121
                            List<Text> right = new List<Text>();
6122
                            List<Text> up = new List<Text>();
6123
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
6124
                            foreach (var loopText in allTexts)
6125
                            {
6126
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
6127
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
6128
                                double originX = 0;
6129
                                double originY = 0;
6130
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6131
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6132

    
6133
                                if (angle < 45)
6134
                                {
6135
                                    // Text 오른쪽
6136
                                    if (textCenterX > originX)
6137
                                        right.Add(loopText);
6138
                                    // Text 왼쪽
6139
                                    else
6140
                                        left.Add(loopText);
6141
                                }
6142
                                else
6143
                                {
6144
                                    // Text 아래쪽
6145
                                    if (textCenterY > originY)
6146
                                        down.Add(loopText);
6147
                                    // Text 위쪽
6148
                                    else
6149
                                        up.Add(loopText);
6150
                                }
6151
                            }
6152

    
6153
                            #endregion
6154

    
6155
                            foreach (var texts in sortTexts)
6156
                            {
6157
                                if (texts.Count == 0)
6158
                                    continue;
6159

    
6160
                                #region 첫번째 Text로 기준 맞춤
6161
                                for (int i = 0; i < texts.Count; i++)
6162
                                {
6163
                                    if (i != 0)
6164
                                    {
6165
                                        Text currentText = texts[i];
6166
                                        Text prevText = texts[i - 1];
6167
                                        double minY = prevText.SPPID.Range[1];
6168
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
6169
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
6170
                                        double _gapX = centerX - centerPrevX;
6171
                                        double _gapY = currentText.SPPID.Range[3] - minY;
6172
                                        MoveText(currentText, _gapX, _gapY);
6173
                                    }
6174
                                }
6175
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
6176
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
6177
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
6178
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
6179
                                rangeMinX.Sort();
6180
                                rangeMinY.Sort();
6181
                                rangeMaxX.Sort();
6182
                                rangeMaxY.Sort();
6183
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
6184
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
6185
                                #endregion
6186
                                #region 정렬
6187
                                Text correctBySymbol = texts[0];
6188
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
6189
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
6190
                                double originX = 0;
6191
                                double originY = 0;
6192
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
6193
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
6194
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
6195
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
6196

    
6197
                                double gapX = 0;
6198
                                double gapY = 0;
6199
                                if (angle < 45)
6200
                                {
6201
                                    // Text 오른쪽
6202
                                    if (textCenterX > originX)
6203
                                    {
6204
                                        gapX = rangeMinX[0] - symbolRange[2];
6205
                                        gapY = allTextCenterY - symbolCenterY;
6206
                                    }
6207
                                    // Text 왼쪽
6208
                                    else
6209
                                    {
6210
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
6211
                                        gapY = allTextCenterY - symbolCenterY;
6212
                                    }
6213
                                }
6214
                                else
6215
                                {
6216
                                    // Text 아래쪽
6217
                                    if (textCenterY > originY)
6218
                                    {
6219
                                        gapX = allTextCenterX - symbolCenterX;
6220
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
6221
                                    }
6222
                                    // Text 위쪽
6223
                                    else
6224
                                    {
6225
                                        gapX = allTextCenterX - symbolCenterX;
6226
                                        gapY = rangeMinY[0] - symbolRange[3];
6227
                                    }
6228
                                }
6229

    
6230
                                foreach (var item in texts)
6231
                                {
6232
                                    MoveText(item, gapX, gapY);
6233
                                    RemodelingAssociationText(item);
6234
                                }
6235
                                #endregion
6236
                            }
6237
                        }
6238
                    }
6239
                }
6240

    
6241
                void MoveText(Text moveText, double x, double y)
6242
                {
6243
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
6244
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
6245
                    moveText.SPPID.Range = new double[] {
6246
                        moveText.SPPID.Range[0] - x,
6247
                        moveText.SPPID.Range[1]- y,
6248
                        moveText.SPPID.Range[2]- x,
6249
                        moveText.SPPID.Range[3]- y
6250
                    };
6251
                }
6252

    
6253
                endTexts.AddRange(allTexts);
6254

    
6255
                ReleaseCOMObjects(targetLabel);
6256
                targetLabel = null;
6257
                ReleaseCOMObjects(representation);
6258
                representation = null;
6259
            }
6260
        }
6261

    
6262
        private void RemodelingAssociationText(Text text)
6263
        {
6264
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
6265
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
6266
            removeLabel.Commit();
6267
            ReleaseCOMObjects(removeLabel);
6268
            removeLabel = null;
6269

    
6270
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
6271
            if (owner != null && owner.GetType() == typeof(Symbol))
6272
            {
6273
                Symbol symbol = owner as Symbol;
6274
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
6275
                if (_LMSymbol != null)
6276
                {
6277
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
6278
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
6279
                    {
6280
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
6281

    
6282
                        if (mapping != null)
6283
                        {
6284
                            double x = 0;
6285
                            double y = 0;
6286

    
6287
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
6288
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
6289
                            if (_LMLabelPersist != null)
6290
                            {
6291
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
6292
                                _LMLabelPersist.Commit();
6293
                            }
6294
                            ReleaseCOMObjects(_LMLabelPersist);
6295
                            _LMLabelPersist = null;
6296
                        }
6297
                    }
6298
                }
6299
                ReleaseCOMObjects(_LMSymbol);
6300
                _LMSymbol = null;
6301
            }
6302
        }
6303

    
6304
        /// <summary>
6305
        /// Note Modeling
6306
        /// </summary>
6307
        /// <param name="note"></param>
6308
        private void NoteModeling(Note note, List<Note> correctList)
6309
        {
6310
            LMSymbol _LMSymbol = null;
6311
            LMItemNote _LMItemNote = null;
6312
            LMAAttribute _LMAAttribute = null;
6313

    
6314
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
6315
            {
6316
                double x = 0;
6317
                double y = 0;
6318

    
6319
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
6320
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
6321
                note.SPPID.SPPID_X = x;
6322
                note.SPPID.SPPID_Y = y;
6323

    
6324
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
6325
                if (_LMSymbol != null)
6326
                {
6327
                    _LMSymbol.Commit();
6328
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6329
                    if (_LMItemNote != null)
6330
                    {
6331
                        _LMItemNote.Commit();
6332
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6333
                        if (_LMAAttribute != null)
6334
                        {
6335
                            _LMAAttribute.set_Value(note.VALUE);
6336
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6337

    
6338
                            double[] range = null;
6339
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
6340
                            {
6341
                                double[] temp = null;
6342
                                GetSPPIDSymbolRange(labelPersist, ref temp);
6343
                                if (temp != null)
6344
                                {
6345
                                    if (range == null)
6346
                                        range = temp;
6347
                                    else
6348
                                    {
6349
                                        range = new double[] {
6350
                                            Math.Min(range[0], temp[0]),
6351
                                            Math.Min(range[1], temp[1]),
6352
                                            Math.Max(range[2], temp[2]),
6353
                                            Math.Max(range[3], temp[3])
6354
                                        };
6355
                                    }
6356
                                }
6357
                            }
6358
                            if (range != null)
6359
                                correctList.Add(note);
6360
                            note.SPPID.Range = range;
6361

    
6362

    
6363
                            _LMItemNote.Commit();
6364
                        }
6365
                    }
6366
                }
6367
            }
6368

    
6369
            if (_LMAAttribute != null)
6370
                ReleaseCOMObjects(_LMAAttribute);
6371
            if (_LMItemNote != null)
6372
                ReleaseCOMObjects(_LMItemNote);
6373
            if (_LMSymbol != null)
6374
                ReleaseCOMObjects(_LMSymbol);
6375
        }
6376

    
6377
        private void NoteCorrectModeling(Note note, List<Note> endList)
6378
        {
6379
            bool needRemodeling = false;
6380
            bool loop = true;
6381
            GridSetting gridSetting = GridSetting.GetInstance();
6382
            while (loop)
6383
            {
6384
                loop = false;
6385
                foreach (var overlap in endList)
6386
                {
6387
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
6388
                    {
6389
                        double tempX = 0;
6390
                        double tempY = 0;
6391
                        bool overlapX = false;
6392
                        bool overlapY = false;
6393
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
6394
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
6395
                        if (overlapY && angle >= 45)
6396
                        {
6397
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
6398
                            double move = gridSetting.Length * count;
6399
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
6400
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
6401
                            needRemodeling = true;
6402
                            loop = true;
6403
                        }
6404
                        if (overlapX && angle <= 45)
6405
                        {
6406
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
6407
                            double move = gridSetting.Length * count;
6408
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
6409
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
6410
                            needRemodeling = true;
6411
                            loop = true;
6412
                        }
6413
                    }
6414
                }
6415
            }
6416

    
6417

    
6418
            if (needRemodeling)
6419
            {
6420
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
6421
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
6422
                note.SPPID.RepresentationId = null;
6423

    
6424
                LMItemNote _LMItemNote = null;
6425
                LMAAttribute _LMAAttribute = null;
6426
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
6427
                if (_LMSymbol != null)
6428
                {
6429
                    _LMSymbol.Commit();
6430
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
6431
                    if (_LMItemNote != null)
6432
                    {
6433
                        _LMItemNote.Commit();
6434
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
6435
                        if (_LMAAttribute != null)
6436
                        {
6437
                            _LMAAttribute.set_Value(note.VALUE);
6438
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
6439
                            _LMItemNote.Commit();
6440

    
6441
                            ReleaseCOMObjects(_LMAAttribute);
6442
                            ReleaseCOMObjects(_LMItemNote);
6443
                        }
6444
                    }
6445
                }
6446

    
6447
                ReleaseCOMObjects(symbol);
6448
                symbol = null;
6449
                ReleaseCOMObjects(_LMItemNote);
6450
                _LMItemNote = null;
6451
                ReleaseCOMObjects(_LMAAttribute);
6452
                _LMAAttribute = null;
6453
                ReleaseCOMObjects(_LMSymbol);
6454
                _LMSymbol = null;
6455
            }
6456

    
6457
            endList.Add(note);
6458
        }
6459

    
6460
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
6461
        {
6462
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6463
            if (modelItem != null)
6464
            {
6465
                foreach (LMRepresentation rep in modelItem.Representations)
6466
                {
6467
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
6468
                    {
6469
                        LMConnector connector = dataSource.GetConnector(rep.Id);
6470
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
6471
                        {
6472
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
6473
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6474
                            if (modelItemIds.Count == 1)
6475
                            {
6476
                                string joinModelItemId = modelItemIds[0];
6477
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6478
                                if (survivorId != null)
6479
                                    break;
6480
                            }
6481
                        }
6482
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
6483
                        {
6484
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
6485
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
6486
                            if (modelItemIds.Count == 1)
6487
                            {
6488
                                string joinModelItemId = modelItemIds[0];
6489
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
6490
                                if (survivorId != null)
6491
                                    break;
6492
                            }
6493
                        }
6494
                    }
6495
                }
6496
            }
6497
        }
6498

    
6499
        /// <summary>
6500
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
6501
        /// </summary>
6502
        /// <param name="x"></param>
6503
        /// <param name="y"></param>
6504
        /// <param name="originX"></param>
6505
        /// <param name="originY"></param>
6506
        /// <param name="SPPIDLabelLocation"></param>
6507
        /// <param name="location"></param>
6508
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDEtcLocationInfo SPPIDLabelLocation, Location location)
6509
        {
6510
            if (location == Location.None)
6511
            {
6512
                x = originX;
6513
                y = originY;
6514
            }
6515
            else
6516
            {
6517
                if (location.HasFlag(Location.Center))
6518
                {
6519
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
6520
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
6521
                }
6522

    
6523
                if (location.HasFlag(Location.Left))
6524
                    x = SPPIDLabelLocation.X1;
6525
                else if (location.HasFlag(Location.Right))
6526
                    x = SPPIDLabelLocation.X2;
6527

    
6528
                if (location.HasFlag(Location.Down))
6529
                    y = SPPIDLabelLocation.Y1;
6530
                else if (location.HasFlag(Location.Up))
6531
                    y = SPPIDLabelLocation.Y2;
6532
            }
6533
        }
6534

    
6535
        /// <summary>
6536
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
6537
        /// 1. Angle Valve
6538
        /// 2. 3개로 이루어진 Symbol Group
6539
        /// </summary>
6540
        /// <returns></returns>
6541
        private List<Symbol> GetPrioritySymbol()
6542
        {
6543
            DataTable symbolTable = document.SymbolTable;
6544
            // List에 순서대로 쌓는다.
6545
            List<Symbol> symbols = new List<Symbol>();
6546

    
6547
            // Angle Valve 부터
6548
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
6549
            {
6550
                if (!symbols.Contains(symbol))
6551
                {
6552
                    double originX = 0;
6553
                    double originY = 0;
6554

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

    
6559
                    SlopeType slopeType1 = SlopeType.None;
6560
                    SlopeType slopeType2 = SlopeType.None;
6561
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
6562
                    {
6563
                        double connectorX = 0;
6564
                        double connectorY = 0;
6565
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
6566
                        if (slopeType1 == SlopeType.None)
6567
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6568
                        else
6569
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
6570
                    }
6571

    
6572
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
6573
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
6574
                        symbols.Add(symbol);
6575
                }
6576
            }
6577

    
6578
            List<Symbol> tempSymbols = new List<Symbol>();
6579
            // Conn 갯수 기준
6580
            foreach (var item in document.SYMBOLS)
6581
            {
6582
                if (!symbols.Contains(item))
6583
                    tempSymbols.Add(item);
6584
            }
6585
            tempSymbols.Sort(SPPIDUtil.SortSymbolPriority);
6586
            symbols.AddRange(tempSymbols);
6587

    
6588
            return symbols;
6589
        }
6590

    
6591
        private void SetPriorityLine(List<Line> lines)
6592
        {
6593
            lines.Sort(SortLinePriority);
6594

    
6595
            int SortLinePriority(Line a, Line b)
6596
            {
6597
                // Branch 없는것부터
6598
                int branchRetval = CompareBranchLine(a, b);
6599
                if (branchRetval != 0)
6600
                {
6601
                    return branchRetval;
6602
                }
6603
                else
6604
                {
6605
                    // Symbol 연결 갯수
6606
                    int connSymbolRetval = CompareConnSymbol(a, b);
6607
                    if (connSymbolRetval != 0)
6608
                    {
6609
                        return connSymbolRetval;
6610
                    }
6611
                    else
6612
                    {
6613
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
6614
                        int connItemRetval = CompareConnItem(a, b);
6615
                        if (connItemRetval != 0)
6616
                        {
6617
                            return connItemRetval;
6618
                        }
6619
                        else
6620
                        {
6621
                            // ConnectedItem이 없는것
6622
                            int noneConnRetval = CompareNoneConn(a, b);
6623
                            if (noneConnRetval != 0)
6624
                            {
6625
                                return noneConnRetval;
6626
                            }
6627
                            else
6628
                            {
6629

    
6630
                            }
6631
                        }
6632
                    }
6633
                }
6634

    
6635
                return 0;
6636
            }
6637

    
6638
            int CompareNotSegmentLine(Line a, Line b)
6639
            {
6640
                List<Connector> connectorsA = a.CONNECTORS
6641
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6642
                    .ToList();
6643

    
6644
                List<Connector> connectorsB = b.CONNECTORS
6645
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6646
                    .ToList();
6647

    
6648
                // 오름차순
6649
                return connectorsB.Count.CompareTo(connectorsA.Count);
6650
            }
6651

    
6652
            int CompareConnSymbol(Line a, Line b)
6653
            {
6654
                List<Connector> connectorsA = a.CONNECTORS
6655
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6656
                    .ToList();
6657

    
6658
                List<Connector> connectorsB = b.CONNECTORS
6659
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
6660
                    .ToList();
6661

    
6662
                // 오름차순
6663
                return connectorsB.Count.CompareTo(connectorsA.Count);
6664
            }
6665

    
6666
            int CompareConnItem(Line a, Line b)
6667
            {
6668
                List<Connector> connectorsA = a.CONNECTORS
6669
                    .Where(conn => conn.ConnectedObject != null &&
6670
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6671
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
6672
                    .ToList();
6673

    
6674
                List<Connector> connectorsB = b.CONNECTORS
6675
                    .Where(conn => conn.ConnectedObject != null &&
6676
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
6677
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
6678
                    .ToList();
6679

    
6680
                // 오름차순
6681
                return connectorsB.Count.CompareTo(connectorsA.Count);
6682
            }
6683

    
6684
            int CompareBranchLine(Line a, Line b)
6685
            {
6686
                List<Connector> connectorsA = a.CONNECTORS
6687
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
6688
                    .ToList();
6689
                List<Connector> connectorsB = b.CONNECTORS
6690
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
6691
                    .ToList();
6692

    
6693
                // 내림차순
6694
                return connectorsA.Count.CompareTo(connectorsB.Count);
6695
            }
6696

    
6697
            int CompareNoneConn(Line a, Line b)
6698
            {
6699
                List<Connector> connectorsA = a.CONNECTORS
6700
                    .Where(conn => conn.ConnectedObject == null)
6701
                    .ToList();
6702

    
6703
                List<Connector> connectorsB = b.CONNECTORS
6704
                    .Where(conn => conn.ConnectedObject == null)
6705
                    .ToList();
6706

    
6707
                // 오름차순
6708
                return connectorsB.Count.CompareTo(connectorsA.Count);
6709
            }
6710
        }
6711

    
6712
        private void SortText(List<Text> texts)
6713
        {
6714
            texts.Sort(Sort);
6715

    
6716
            int Sort(Text a, Text b)
6717
            {
6718
                int yRetval = CompareY(a, b);
6719
                if (yRetval != 0)
6720
                {
6721
                    return yRetval;
6722
                }
6723
                else
6724
                {
6725
                    return CompareX(a, b);
6726
                }
6727
            }
6728

    
6729
            int CompareY(Text a, Text b)
6730
            {
6731
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6732
            }
6733

    
6734
            int CompareX(Text a, Text b)
6735
            {
6736
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6737
            }
6738
        }
6739
        private void SortNote(List<Note> notes)
6740
        {
6741
            notes.Sort(Sort);
6742

    
6743
            int Sort(Note a, Note b)
6744
            {
6745
                int yRetval = CompareY(a, b);
6746
                if (yRetval != 0)
6747
                {
6748
                    return yRetval;
6749
                }
6750
                else
6751
                {
6752
                    return CompareX(a, b);
6753
                }
6754
            }
6755

    
6756
            int CompareY(Note a, Note b)
6757
            {
6758
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6759
            }
6760

    
6761
            int CompareX(Note a, Note b)
6762
            {
6763
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6764
            }
6765
        }
6766

    
6767
        private void SortBranchLines()
6768
        {
6769
            BranchLines.Sort(SortBranchLine);
6770
            int SortBranchLine(Line a, Line b)
6771
            {
6772
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6773
                 x.ConnectedObject.GetType() == typeof(Line) &&
6774
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6775
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6776

    
6777
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6778
                 x.ConnectedObject.GetType() == typeof(Line) &&
6779
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6780
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6781

    
6782
                // 내림차순
6783
                return countA.CompareTo(countB);
6784
            }
6785
        }
6786

    
6787
        
6788

    
6789
        private string GetSPPIDFileName(LMModelItem modelItem)
6790
        {
6791
            string symbolPath = null;
6792
            foreach (LMRepresentation rep in modelItem.Representations)
6793
            {
6794
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6795
                {
6796
                    symbolPath = rep.get_FileName();
6797
                    break;
6798
                }
6799
            }
6800
            return symbolPath;
6801
        }
6802

    
6803
        private string GetSPPIDFileName(string modelItemId)
6804
        {
6805
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6806
            string symbolPath = null;
6807
            foreach (LMRepresentation rep in modelItem.Representations)
6808
            {
6809
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6810
                {
6811
                    symbolPath = rep.get_FileName();
6812
                    break;
6813
                }
6814
            }
6815
            ReleaseCOMObjects(modelItem);
6816
            return symbolPath;
6817
        }
6818

    
6819
        /// <summary>
6820
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6821
        /// </summary>
6822
        /// <param name="graphicOID"></param>
6823
        /// <param name="milliseconds"></param>
6824
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6825
        {
6826
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6827
            {
6828
                double minX = 0;
6829
                double minY = 0;
6830
                double maxX = 0;
6831
                double maxY = 0;
6832
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6833
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6834

    
6835
                Thread.Sleep(milliseconds);
6836
            }
6837
        }
6838

    
6839
        /// <summary>
6840
        /// ComObject를 Release
6841
        /// </summary>
6842
        /// <param name="objVars"></param>
6843
        public void ReleaseCOMObjects(params object[] objVars)
6844
        {
6845
            if (objVars != null)
6846
            {
6847
                int intNewRefCount = 0;
6848
                foreach (object obj in objVars)
6849
                {
6850
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6851
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6852
                }
6853
            }
6854
        }
6855

    
6856
        /// IDisposable 구현
6857
        ~AutoModeling()
6858
        {
6859
            this.Dispose(false);
6860
        }
6861

    
6862
        private bool disposed;
6863
        public void Dispose()
6864
        {
6865
            this.Dispose(true);
6866
            GC.SuppressFinalize(this);
6867
        }
6868

    
6869
        protected virtual void Dispose(bool disposing)
6870
        {
6871
            if (this.disposed) return;
6872
            if (disposing)
6873
            {
6874
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6875
            }
6876
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6877
            this.disposed = true;
6878
        }
6879
    }
6880
}
클립보드 이미지 추가 (최대 크기: 500 MB)