Ejemplo n.º 1
0
        /// <summary>
        /// 界面级别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        // private void appChange(object sender, Autodesk.Revit.DB.Events.DocumentChangedEventArgs e)
        //{
        //    TaskDialog.Show("已改", "已改动");
        //}

        ///文档级别事件
        //private void docClosing(object sender, Autodesk.Revit.DB.Events.DocumentClosedEventArgs e)
        //{
        //    TaskDialog.Show("关闭", "已关闭");
        //}

        private void IdlingTest(object sender, Autodesk.Revit.UI.Events.IdlingEventArgs e)
        {
            UIApplication m_uiapp = sender as UIApplication;

            Autodesk.Revit.DB.Document m_doc = m_uiapp.ActiveUIDocument.Document;
            Transaction trans = new Transaction(m_doc, "idling");

            trans.Start();
            ElementId id  = new ElementId(194987);
            TextNote  tn  = m_doc.GetElement(id) as TextNote;
            string    str = tn.Text;
            int       i   = 0;

            int.TryParse(str, out i);
            tn.Text = (i + 1).ToString();
            trans.Commit();
        }
Ejemplo n.º 2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;
            View       view  = uidoc.ActiveView;


            bool iscontinue = true;

            do
            {
                TextNote textnote = null;
                Room     room     = null;
                try
                {
                    textnote = SelectText(uidoc);
                    room     = SelectRoom(uidoc);
                    if (room == null || textnote == null)
                    {
                        TaskDialog.Show("wrong", "貌似获取到的房间或文字有点问题,请重新获取."); continue;
                    }
                }
                catch
                {
                    iscontinue = false;
                    continue;
                }

                //transaction

                using (Transaction transaction = new Transaction(doc))
                {
                    transaction.Start("更改房间标记");

                    string text = textnote.Text;

                    room.Name = text;

                    transaction.Commit();
                }
            }while (iscontinue);



            return(Result.Succeeded);
        }
Ejemplo n.º 3
0
        void SetTextAlignment(TextNote textNote)
        {
            Document doc = textNote.Document;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("AlignTextNote");

                Parameter p = textNote.get_Parameter(
                    BuiltInParameter.TEXT_ALIGN_VERT);

                p.Set((Int32)
                      TextAlignFlags.TEF_ALIGN_MIDDLE);

                t.Commit();
            }
        }
Ejemplo n.º 4
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get application and documnet objects
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;
            //TextNoteOptions options = new TextNoteOptions();
            ElementId typeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
            Collector co     = new Collector();
            //int i = 1;

            int i = co.GetMaxValue(doc);
            IList <Reference> pickedObjs = uidoc.Selection.PickObjects(ObjectType.Element, "Select Multiple Elements");
            List <ElementId>  ids        = (from Reference r in pickedObjs select r.ElementId).ToList();

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("transaction");
                if (pickedObjs != null && pickedObjs.Count > 0)
                {
                    foreach (ElementId eid in ids)
                    {
                        Element e = doc.GetElement(eid);
                        //string strng = "random";
                        //FamilyInstance faminst = e as FamilyInstance;
                        LocationPoint locPoint = e.Location as LocationPoint;
                        if (null != locPoint)
                        {
                            XYZ      point_a = locPoint.Point;
                            TextNote note    = TextNote.Create(doc, view.Id, point_a, i.ToString(), typeId);
                        }
                        else
                        {
                            LocationCurve locCurve = e.Location as LocationCurve;
                            XYZ           point_a  = locCurve.Curve.Evaluate(0.5, true);
                            TextNote      note     = TextNote.Create(doc, view.Id, point_a, i.ToString(), typeId);
                        }
                        i += 1;
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 5
0
        //private void btnCancel_Click(object sender, EventArgs e)
        //{

        //    //this.Close();
        //}

        #region convertTextNotesToUpperByView
        private void convertTextNotesToUpperByView()
        {
            // Iterate through the document and find all the TextNote elements
            FilteredElementCollector collector = new FilteredElementCollector(document, document.ActiveView.Id);

            collector.OfClass(typeof(TextNote));
            if (collector.GetElementCount() == 0)
            {
                return;
            }

            // Record all TextNotes that are not yet formatted to be 'AllCaps'
            ElementSet textNotesToUpdate = new Autodesk.Revit.DB.ElementSet();

            foreach (Element element in collector)
            {
                TextNote textNote = (TextNote)element;

                // Extract the FormattedText from the TextNote
                FormattedText formattedText = textNote.GetFormattedText();

                if (formattedText.GetAllCapsStatus() != FormatStatus.All)
                {
                    textNotesToUpdate.Insert(textNote);
                }
            }

            // Check whether we found any TextNotes that need to be formatted
            if (textNotesToUpdate.IsEmpty)
            {
                //Do something if there are no notes to format
                TaskDialog.Show("Nothing to do!", "There are no Text Notes to change to uppercase!");
            }

            // Apply the 'AllCaps' formatting to the TextNotes that still need it.
            using (frmConvertTextNotes frm = new frmConvertTextNotes(document))
            {
                foreach (TextNote textNote in textNotesToUpdate)
                {
                    Autodesk.Revit.DB.FormattedText formattedText = textNote.GetFormattedText();
                    formattedText.SetAllCapsStatus(true);
                    textNote.SetFormattedText(formattedText);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string    text  = "";
            TextStyle style = null;

            if (!DA.GetData <string>(0, ref text))
            {
                return;
            }
            if (!DA.GetData <TextStyle>(1, ref style))
            {
                return;
            }

            TextNote tn = new TextNote(text, style);

            DA.SetData(0, tn);
        }
Ejemplo n.º 7
0
        public TextNote SelectText(UIDocument UIdoc)
        {
            ISelectionFilter selecFilter = new TextNoteSelectionFilter();

            Reference selectedElement = UIdoc.Selection.PickObject(ObjectType.Element, selecFilter);

            Element  e = UIdoc.Document.GetElement(selectedElement.ElementId);
            TextNote t = e as TextNote;

            if (t != null)
            {
                TextNote selectedTextNote = t;
                Debug("selected elements" + selectedTextNote.ToString());
                return(selectedTextNote);
            }

            return(null);
        }
        public static void Run()
        {
            ScrapbookHelper scrapbookHelper = new ScrapbookHelper();

            var tempoNote = new TextNote("DRAFT");

            scrapbookHelper.Add(new PictureNote());
            scrapbookHelper.Add(tempoNote);
            scrapbookHelper.Add(new TextNote());
            scrapbookHelper.Add(new ScribbleNote());
            scrapbookHelper.Remove(tempoNote);

            Console.WriteLine();
            Console.WriteLine("FINAL LIST:");
            foreach (Note note in scrapbookHelper.Notes)
            {
                Console.WriteLine($"{note:TC}");
            }
        }
Ejemplo n.º 9
0
        public void DrawValue()
        {
            TextNote textNote    = Value as TextNote;
            XYZ      tempOrigion = GetLocation();

            if (textNote != null)
            {
                View tempView = ExternalDataWrapper.Current.Doc.GetElement(textNote.OwnerViewId) as View;
                if (tempView == null)
                {
                    return;
                }

                #region 处理标签宽度
                double scale = tempView.Scale;
                textNote.Width = Width.ToApi() / scale;
                #endregion

                //标签宽度,与表格同宽
                #region 处理水平对齐偏移
                double tempOffsetWidth = Width.ToApi() / 2;
                int    hashcode        = textNote.GetParameterInteger(BuiltInParameter.TEXT_ALIGN_HORZ);
                if (hashcode == TextAlignFlags.TEF_ALIGN_LEFT.GetHashCode())
                {
                    tempOffsetWidth = 0;
                }
                else if (hashcode == TextAlignFlags.TEF_ALIGN_RIGHT.GetHashCode())
                {
                    tempOffsetWidth = Width.ToApi();
                }
                XYZ result = tempOrigion.OffsetPoint(XYZ.BasisX, tempOffsetWidth);
                #endregion
                BoundingBoxXYZ bb = textNote.get_BoundingBox(tempView);
                if (bb != null)
                {
                    double textHeight = bb.Max.Y - bb.Min.Y;
                    double offset     = (Height.ToApi() - textHeight) / 2;
                    result = result.OffsetPoint(-XYZ.BasisY, offset);
                }
                textNote.Document.MoveElementExt(textNote.Id, result.Subtract(textNote.Coord));
            }
        }
Ejemplo n.º 10
0
        //创建门窗标记字体实例
        public TextNote AddNewTextNote(Document doc, ElementId viewId, XYZ textLoc, String str, double angle)
        {
            IList <Element> textNoteTypes = (new FilteredElementCollector(doc)).OfClass(typeof(TextNoteType)).ToElements();
            string          tntfield      = "Arial Narrow-2.0-1.00-HDDN";//目标文字注释类型
            ElementId       tntId         = null;

            foreach (Element tnt in textNoteTypes)
            {
                if (tnt.Name == tntfield)//需要确认是否存在门窗标记类型的文字注释
                {
                    tntId = tnt.Id;
                }
            }
            TextNoteOptions opts = new TextNoteOptions(tntId);

            opts.Rotation = angle;
            TextNote textNote = TextNote.Create(doc, viewId, textLoc, str, opts);

            return(textNote);
        }
Ejemplo n.º 11
0
        public void SerializesTextNotes()
        {
            var id       = "someid";
            var uid      = "someuid";
            var archived = true;
            var title    = "sometitle";
            var text     = "some text";
            var expected = new TextNote
            {
                Id       = id,
                UID      = uid,
                Archived = archived,
                Title    = title,
                Text     = text
            };
            var json     = JsonConvert.SerializeObject(expected, converter);
            var note     = JsonConvert.DeserializeObject <Note>(json, converter);
            var textNote = Assert.IsAssignableFrom <TextNote>(note);

            Assert.Equal(expected, textNote);
        }
Ejemplo n.º 12
0
        public void HandlesCamelCase()
        {
            var id       = "someid";
            var uid      = "someuid";
            var archived = true;
            var title    = "sometitle";
            var text     = "some text";
            var expected = new TextNote
            {
                Id       = id,
                UID      = uid,
                Archived = archived,
                Title    = title,
                Text     = text
            };
            var json     = $"{{ 'id': '{id}', 'type': 'TextNote', 'uid': '{uid}', 'archived': {archived.ToString().ToLower()}, 'title': '{title}', 'text': '{text}' }}";
            var note     = JsonConvert.DeserializeObject <Note>(json, converter);
            var textNote = Assert.IsAssignableFrom <TextNote>(note);

            Assert.Equal(expected, textNote);
        }
Ejemplo n.º 13
0
        public DoorInformation GetDoorInfo(UIDocument uidoc)
        {
            Document doc = uidoc.Document;

            //selection
            DetaiLineFilter detaillinefilter = new DetaiLineFilter();
            TextFilter      textfilter       = new TextFilter();
            Reference       refdetailline1   = null;
            Reference       refdetailline2   = null;
            Reference       reftext          = null;

            try
            {
                refdetailline1 = uidoc.Selection.PickObject(ObjectType.Element, detaillinefilter, "选择第一根边线.");
                refdetailline2 = uidoc.Selection.PickObject(ObjectType.Element, detaillinefilter, "选择第二根边线.");
                reftext        = uidoc.Selection.PickObject(ObjectType.Element, textfilter, "选择门标记.");
            }
            catch
            {
                return(null);
            }

            List <Line> lines = new List <Line>();

            lines.Add((doc.GetElement(refdetailline1) as DetailLine).GeometryCurve as Line);
            lines.Add((doc.GetElement(refdetailline2) as DetailLine).GeometryCurve as Line);
            TextNote text = doc.GetElement(reftext) as TextNote;

            //get family and symbol
            string str = text.Text;

            str = ProcessString(str);
            Family          doorfamily   = GetDoorFamily(doc, str);
            FamilySymbol    doorsymbol   = GetDoorSymbol(doc, doorfamily, str);
            XYZ             doorlocation = GetLoaction(lines);
            DoorInformation doorinfo     = new DoorInformation(doorsymbol, doorlocation);

            return(doorinfo);
        }
        public async void UpdatesNoteIfIdAndUIDMatchExisting(string uid)
        {
            var toUpdate = uid == "uid1" ? note1 : note2;
            var updated  = new TextNote
            {
                Id       = toUpdate.Id,
                UID      = uid,
                Archived = !toUpdate.Archived,
                Title    = "new title",
                Text     = "new text"
            };

            var result = await repo.Update(updated);

            var expected = expectedCollection;

            expected.Remove(toUpdate);
            expected.Add(updated);

            Assert.Equal(updated, result);
            AssertCollectionEquals(expected);
        }
Ejemplo n.º 15
0
        //Get exisitng textnotes
        public int GetMaxValue(Document doc)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            ICollection <Element>    TextNotes = collector.OfCategory(BuiltInCategory.OST_TextNotes).WhereElementIsNotElementType().ToElements();

            List <int> Values = new List <int>();

            foreach (Element e in collector)
            {
                TextNote tn = e as TextNote;
                Values.Add(Int32.Parse(tn.Text));
            }

            if (TextNotes.Count > 0)
            {
                return(Values.Max() + 1);
            }
            else
            {
                return(1);
            }
        }
Ejemplo n.º 16
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication application      = commandData.Application;
            UIDocument    activeUIDocument = application.ActiveUIDocument;
            Application   application2     = application.Application;
            Document      doc = activeUIDocument.Document;
            Selection     sel = activeUIDocument.Selection;
            //while (iscontinue)
            //{
            //    try
            //    {
            //        Reference reference = sel.PickObject(ObjectType.Element,/* new Filterdimention(),*/ "Select Dimension");
            //        Dimension dimension = doc.GetElement(reference) as Dimension;
            //        CSAZDimCallout dim = new CSAZDimCallout(doc, dimension, new XYZ(1, 0, 0));
            //        CreateTextNote(doc, dim);
            //    }
            //    catch
            //    {
            //        iscontinue = false;
            //    }
            //}
            Reference      reference = sel.PickObject(ObjectType.Element, /* new Filterdimention(),*/ "Select Dimension");
            Dimension      dimension = doc.GetElement(reference) as Dimension;
            CSAZDimCallout dim       = new CSAZDimCallout(doc, dimension, new XYZ(1, 0, 0));
            TextNote       textNote  = null;

            CreateTextNote(doc, dim, sel, ref textNote);
            Transaction tran = new Transaction(doc, "Create Line");

            tran.Start();
            PLane3D pLane3D = new PLane3D(doc.ActiveView.Origin, doc.ActiveView.ViewDirection);
            double  value   = textNote.GetMaximumAllowedWidth();
            XYZ     p1      = Timdiemdimngang(dim.Endpoint, dim.VectorDirection, 3);
            var     dline   = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(pLane3D.ProjectPointOnPlane(dim.Endpoint), pLane3D.ProjectPointOnPlane(p1)));

            tran.Commit();
            return(Result.Succeeded);
        }
Ejemplo n.º 17
0
        public static void ListLineStyles(UIDocument uiDoc)
        {
            Document  currentDoc = uiDoc.Document;
            Selection sel        = uiDoc.Selection;
            XYZ       BasePt     = sel.PickPoint();

            FilteredElementCollector LineCollector = new FilteredElementCollector(currentDoc);
            List <ElementId>         Lines         = LineCollector.OfCategory(BuiltInCategory.OST_Lines).ToElementIds().ToList();
            FilteredElementCollector txtCollector  = new FilteredElementCollector(currentDoc);
            ElementId txtnoteTypeId = txtCollector.OfCategory(BuiltInCategory.OST_TextNotes).FirstElement().GetTypeId();

            int adjustment = 10;
            Dictionary <string, CurveElement> LineStyles = new Dictionary <string, CurveElement>();

            for (int i = 0; i < Lines.Count(); i++)
            {
                CurveElement l = currentDoc.GetElement(Lines[i]) as CurveElement;
                if (!LineStyles.Keys.Contains(l.LineStyle.Name))
                {
                    LineStyles.Add(l.LineStyle.Name, l);
                }
            }
            List <string> StyleName = LineStyles.Keys.ToList();

            StyleName.Sort();
            for (int i = 0; i < StyleName.Count(); i++)
            {
                XYZ startpoint = new XYZ(BasePt.X, (BasePt.Y - (adjustment * i)), 0);
                XYZ endpoint   = new XYZ((BasePt.X + (adjustment * 3)), (BasePt.Y - (adjustment * i)), 0);
                XYZ TextPoint  = new XYZ(BasePt.X + (adjustment * 4), (BasePt.Y - (adjustment * i)), 0);

                Curve       baseCurve = Line.CreateBound(startpoint, endpoint) as Curve;
                DetailCurve addedLine = currentDoc.Create.NewDetailCurve(uiDoc.ActiveView, baseCurve);

                TextNote txNote = TextNote.Create(currentDoc, uiDoc.ActiveView.Id, TextPoint, StyleName[i], txtnoteTypeId);
                addedLine.LineStyle = LineStyles[StyleName[i]].LineStyle;
            }
        }
Ejemplo n.º 18
0
        public IList <TextNote> SelectText(UIDocument UIdoc)
        {
            IList <Reference> selectedElements  = new List <Reference>();
            IList <TextNote>  selectedTextNotes = new List <TextNote>();

            ISelectionFilter selecFilter = new TextNoteSelectionFilter();

            selectedElements = UIdoc.Selection.PickObjects(ObjectType.Element, selecFilter);

            Debug("selected elements" + selectedElements.Count);

            foreach (Reference r in selectedElements)
            {
                Element  e = UIdoc.Document.GetElement(r.ElementId);
                TextNote t = e as TextNote;
                if (t != null)
                {
                    selectedTextNotes.Add(t);
                    Debug("selected elements" + selectedTextNotes.Count);
                }
            }

            return(selectedTextNotes);
        }
Ejemplo n.º 19
0
        public static void Update(UIApplication uiapp)
        {
            Document  doc = uiapp.ActiveUIDocument.Document;
            ElementId eid = uiapp.ActiveUIDocument.Selection.GetElementIds().FirstOrDefault();

            try
            {
                using (Transaction tran = new Transaction(doc, "Text note updated"))
                {
                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
                    {
                        tran.Start();
                        string   textNoteContent = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
                        TextNote existingNote    = doc.GetElement(eid) as TextNote;
                        existingNote.Text = textNoteContent;
                        tran.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
        } //close method
Ejemplo n.º 20
0
        public static void EditTextStyles(UIDocument uiDoc)
        {
            Document         currentDoc      = uiDoc.Document;
            Selection        sel             = uiDoc.Selection;
            ISelectionFilter selectionFilter = new TextSelectionFilter();

            Reference ChangedObject  = sel.PickObject(ObjectType.Element, selectionFilter);
            TextNote  ChangedElement = currentDoc.GetElement(ChangedObject.ElementId) as TextNote;

            Reference    NewObject  = sel.PickObject(ObjectType.Element, selectionFilter);
            TextNote     NewElement = currentDoc.GetElement(NewObject.ElementId) as TextNote;
            TextNoteType type       = NewElement.TextNoteType;

            TextNoteType oldType = ChangedElement.TextNoteType;

            FilteredElementCollector TextCollector = new FilteredElementCollector(currentDoc);
            List <ElementId>         Notes         = TextCollector.OfCategory(BuiltInCategory.OST_TextNotes).ToElementIds().ToList();

            foreach (ElementId EID in Notes)
            {
                TextNote TN = currentDoc.GetElement(EID) as TextNote;
                if (TN.TextNoteType.Name == oldType.Name)
                {
                    if (TN.GroupId == ElementId.InvalidElementId)
                    {
                        TN.TextNoteType = type;
                    }
                    else
                    {
                        Group group = currentDoc.GetElement(TN.GroupId) as Group;
                    }
                }
            }

            currentDoc.Delete(oldType.Id);
        }
Ejemplo n.º 21
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            try
            {
                IList <Reference> textToDelete = uidoc.Selection.PickObjects(ObjectType.Element, "Select text to delete");

                ICollection <ElementId> textNoteTypes = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)).ToElementIds();

                using (Transaction t = new Transaction(doc, "Place text"))
                {
                    t.Start();

                    foreach (Reference textReference in textToDelete)
                    {
                        TextNote  textNoteElement = doc.GetElement(textReference) as TextNote;
                        ElementId eid             = textNoteTypes.Where(x => x == textNoteElement.GetTypeId()).First();
                        doc.Delete(eid);
                    }
                    t.Commit();
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Handler method for ViewPrinting event.
        /// This method will dump EventArgument information of event firstly and then create TextNote element for this view.
        /// View print will be canceled if TextNote creation failed.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event arguments of ViewPrinting event.</param>
        public void AppViewPrinting(object sender, Autodesk.Revit.DB.Events.ViewPrintingEventArgs e)
        {
            // Setup log file if it still is empty
            if (null == m_eventsLog)
            {
                SetupLogFiles();
            }
            //
            // header information
            Trace.WriteLine(System.Environment.NewLine + "View Print Start: ------------------------");
            //
            // Dump the events arguments
            DumpEventArguments(e);
            //
            // Create TextNote for current view, cancel the event if TextNote creation failed
            bool failureOccured = false; // Reserves whether failure occurred when create TextNote

            try
            {
                String strText = String.Format("Printer Name: {0}{1}User Name: {2}",
                                               e.Document.PrintManager.PrinterName, System.Environment.NewLine, System.Environment.UserName);
                //
                // Use non-debug compile symbol to write constant text note
#if !(Debug || DEBUG)
                strText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#endif
                using (Transaction eventTransaction = new Transaction(e.Document, "External Tool"))
                {
                    eventTransaction.Start();
                    TextNoteOptions options = new TextNoteOptions();
                    options.HorizontalAlignment = HorizontalTextAlignment.Center;
                    options.TypeId = e.Document.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                    TextNote newTextNote = TextNote.Create(e.Document, e.View.Id, XYZ.Zero, strText, options);
                    eventTransaction.Commit();

                    // Check to see whether TextNote creation succeeded
                    if (null != newTextNote)
                    {
                        Trace.WriteLine("Create TextNote element successfully...");
                        m_newTextNoteId = newTextNote.Id;
                    }
                    else
                    {
                        failureOccured = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                failureOccured = true;
                Trace.WriteLine("Exception occurred when creating TextNote, print will be canceled, ex: " + ex.Message);
            }
            finally
            {
                // Cancel the TextNote creation when failure occurred, meantime the event is cancellable
                if (failureOccured && e.Cancellable)
                {
                    e.Cancel();
                }
            }
        }
Ejemplo n.º 23
0
        public void CreateTextNote(Document doc, Dictionary <string, List <string> > dic, TextNoteType textNoteType, Selection sel)
        {
            var point = sel.PickPoint();

            if (doc.ActiveView.IsAssemblyView)
            {
                XYZ    direction    = doc.ActiveView.UpDirection;
                string assemblyname = (doc.GetElement(doc.ActiveView.AssociatedAssemblyInstanceId) as AssemblyInstance).Name;
                var    list         = dic[assemblyname].ToList();
                list.Sort();
                Sortliststring(list);
                if (direction.X != 0)
                {
                    using (Transaction tran = new Transaction(doc, "Create new type text"))
                    {
                        XYZ xYZ = XYZ.Zero;
                        tran.Start();
                        for (int i = 0, j = 0; i < list.Count; i++, j += 1)
                        {
                            if (i == 0)
                            {
                                var p2 = new XYZ(point.X, point.Y, point.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                            else
                            {
                                var p2 = new XYZ(xYZ.X, xYZ.Y, xYZ.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                        }
                        tran.Commit();
                    }
                }
                if (direction.Y != 0)
                {
                    using (Transaction tran = new Transaction(doc, "Create new type text"))
                    {
                        XYZ xYZ = XYZ.Zero;
                        tran.Start();
                        for (int i = 0, j = 0; i < list.Count; i++, j += 1)
                        {
                            if (i == 0)
                            {
                                var p2 = new XYZ(point.X, point.Y + 0.016, point.Z);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                            else
                            {
                                var p2 = new XYZ(xYZ.X, xYZ.Y + 0.016, xYZ.Z);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                        }
                        tran.Commit();
                    }
                }
                if (direction.Z != 0)
                {
                    using (Transaction tran = new Transaction(doc, "Create new type text"))
                    {
                        XYZ xYZ = XYZ.Zero;
                        tran.Start();
                        for (int i = 0, j = 0; i < list.Count; i++, j += 1)
                        {
                            if (i == 0)
                            {
                                var p2 = new XYZ(point.X, point.Y, point.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                            else
                            {
                                var p2 = new XYZ(xYZ.X, xYZ.Y, xYZ.Z + 0.016);
                                xYZ = p2;
                                TextNote textNote = TextNote.Create(doc, doc.ActiveView.Id, xYZ, list[i], textNoteType.Id);
                            }
                        }
                        tran.Commit();
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication app = commandData.Application;
            UIDocument    doc = app.ActiveUIDocument;

            //check if there is anything selected
            if (doc.Selection.GetElementIds().Count == 0)
            {
                message = "Nothing Selected!\nPlease select the text notes you want to align and try again.";
                return(Result.Failed);
            }

            //check is there are textNotes in the current selection
            List <ElementId> ids = new List <ElementId>();

            foreach (ElementId id in doc.Selection.GetElementIds())
            {
                ids.Add(id);
            }
            FilteredElementCollector col = new FilteredElementCollector(doc.Document, ids);

            col.OfClass(typeof(TextNote));
            if (col.ToElements().Count == 0)
            {
                message = "No Text Notes selected!\nPlease select the text notes you want to align and try again.";
                return(Result.Failed);
            }

            //at this point we know that text notes are selected so we can proceed.
            TaskDialog td = new TaskDialog("Justification")
            {
                MainInstruction = "Select Justification",
                MainContent     = "Select a justification option from the list below and then select the text note object to align to.",
                CommonButtons   = TaskDialogCommonButtons.Cancel
            };

            td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1,
                              "Left Justified", "This will set all selected text notes to have left justification.");
            td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2,
                              "Centre Justified", "This will set all selected text notes to have centre justification.");
            td.AddCommandLink(TaskDialogCommandLinkId.CommandLink3,
                              "Right Justified", "This will set all selected text notes to have right justification.");
            td.AddCommandLink(TaskDialogCommandLinkId.CommandLink4,
                              "Match Selection", "This will set all selected text notes to have the same justification as the select alignment text note.");

            //get the results from the task dialog
            TaskDialogResult result    = td.Show();
            TextAlignment    alignment = TextAlignment.NoChange;

            switch (result)
            {
            case TaskDialogResult.Cancel:
                return(Result.Cancelled);

            case TaskDialogResult.CommandLink2:
                alignment = TextAlignment.AlignCentre;
                break;

            case TaskDialogResult.CommandLink3:
                alignment = TextAlignment.AlignRight;
                break;

            case TaskDialogResult.CommandLink4:
                alignment = TextAlignment.MatchSelection;
                break;

            case TaskDialogResult.CommandLink1:
            default:
                alignment = TextAlignment.AlignLeft;
                break;
            }

            //clear current selection and ask the user to select the alignment text note
            doc.Selection.SetElementIds(new List <ElementId>());
            ISelectionFilter filter = new TextNoteSelectionFilter();
            Reference        picked = doc.Selection.PickObject(ObjectType.Element, filter, "Select the text note to align to.");

            //check that the user picked something
            if (picked == null)
            {
                message = "Nothing selected!\nYou did not select a text note to align to.";
                return(Result.Failed);
            }

            //start a new transaction
            Transaction t = new Transaction(doc.Document);

            t.Start("KrispCAD Text Align");

            TextNote        alignObject  = doc.Document.GetElement(picked.ElementId) as TextNote;
            double          xValue       = alignObject.Coord.X;
            ProjectLocation curLocation  = doc.Document.ActiveProjectLocation;
            ProjectPosition projPosition = curLocation.get_ProjectPosition(alignObject.Coord);

            XYZ orign = XYZ.Zero;
            XYZ up    = doc.ActiveView.UpDirection;

            //TaskDialog.Show("DEBUG", string.Format("Up Direction: ({0}, {1}, {2}))", up.X, up.Y, up.Z));
            // check page for shortest distance calc: http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment

            Parameter param;

            //if the user select "Match Selection" for justification, get that now
            if (alignment == TextAlignment.MatchSelection)
            {
                param     = alignObject.get_Parameter(BuiltInParameter.TEXT_ALIGN_HORZ);
                alignment = (TextAlignment)param.AsInteger();
            }

            //apply the alignment and justification to all selected text notes
            IEnumerable <TextNote> textNotes = col.Cast <TextNote>();

            foreach (TextNote tn in textNotes)
            {
                param = tn.get_Parameter(BuiltInParameter.TEXT_ALIGN_HORZ);
                param.Set((int)alignment);
                double dist = MathUtils.DistanceToLine2D(new double[] { orign.X, orign.Y }, new double[] { up.X, up.Y }, new double[] { tn.Coord.X, tn.Coord.Y }, false);
                TaskDialog.Show("DEBUG", string.Format("Distance from line described by UP ({0}, {1}) to point ({2}, {3}) = {4}", up.X, up.Y, tn.Coord.X, tn.Coord.Y, dist));
                tn.Coord = new XYZ(xValue, tn.Coord.Y, tn.Coord.Z);
            }

            //commit the transaction
            t.Commit();

            return(Result.Succeeded);
        }
Ejemplo n.º 25
0
        public void PasteInTree(IdeaNote parent, int index)
        {
            // Prefer pasting a note oveer anything else
            if (Clipboard.ContainsData("IdeaNote"))
            {
                if (ImportNote((byte[])Clipboard.GetData("IdeaNote"), parent, index)) return;
            }

            // If the clipboard has file drops, add them as notes
            if (Clipboard.ContainsFileDropList())
            {
                StringCollection fileDrops = Clipboard.GetFileDropList();
                if (fileDrops?.Count > 0)
                {
                    LoadFiles(fileDrops.Cast<string>().ToList(), false, parent, index);
                    return;
                }
            }

            // If the clipboard has text, add it as a new text note
            if (Clipboard.ContainsText(TextDataFormat.Rtf))
            {
                TextNote newNote = new TextNote();
                AddNote(newNote, parent, index);
                newNote.Rtf = Clipboard.GetText(TextDataFormat.Rtf);
                return;
            }
            if (Clipboard.ContainsText())
            {
                TextNote newNote = new TextNote();
                AddNote(newNote, parent, index);
                newNote.SetRtfFromPlainText(Clipboard.GetText());
                return;
            }
        }
Ejemplo n.º 26
0
        public override TextNote ConvertToTextNote()
        {
            TextNote newNote = new TextNote()
            {
                ExplicitName = this.ExplicitName,
                IsExpanded = this.IsExpanded,
                IsSelected = this.IsSelected
            };
            newNote.Ideas = Ideas;
            
            newNote.AddParagraph(Now.ToString($"Now: dddd, MMMM d{(NowYear ? ", yyy" : string.Empty)}{(NowTime ? " h:mm tt" : string.Empty)}"));
            newNote.AddParagraph(string.Empty);
            newNote.AddParagraph("Events:");
            foreach (var timelineEvent in Events)
            {
                newNote.AddParagraph(timelineEvent.Date.ToString($"dddd, MMMM dd{(timelineEvent.UseYear ? ", yyy" : string.Empty)}{(timelineEvent.UseTime ? " h:mm tt" : string.Empty)}"));
                newNote.AddParagraph(string.Empty);
                Xceed.Wpf.Toolkit.RichTextBox rtb = new Xceed.Wpf.Toolkit.RichTextBox();
                rtb.Text = timelineEvent.Rtf;
                rtb.SelectAll();
                rtb.Copy();
                newNote.PasteToRtf();
            }

            return newNote;
        }
Ejemplo n.º 27
0
        public override TextNote ConvertToTextNote()
        {
            TextNote newNote = new TextNote()
            {
                ExplicitName = this.ExplicitName,
                IsExpanded = this.IsExpanded,
                IsSelected = this.IsSelected
            };
            newNote.Ideas = Ideas;
            
            newNote.AddParagraph(GetPlotString());
            newNote.AddParagraph(string.Empty);
            foreach (var line in CharacterConflict.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Backgrounds.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Resolutions.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Traits.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Settings.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Themes.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Genres.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);

            return newNote;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Sets up the scores
        /// These are simple TextNotes
        /// </summary>
        private void SetupScores()
        {
            FilteredElementCollector collector = new FilteredElementCollector(_dbDoc);
            IEnumerable<Element> noteElements = collector.OfClass(typeof(TextNote)).ToElements();
            foreach (Element e in noteElements)
            {
                TextNote note = e as TextNote;
                if (note.Text.Contains(X_SCORE_PRE_TEXT))
                {
                    //Player X score
                    _xScore = note;

                }
                else if (note.Text.Contains(O_SCORE_PRE_TEXT))
                {
                    //player o score
                    _oScore = note;
                }
            }
        }
Ejemplo n.º 29
0
 public TextNote NewTextNote(IdeaNote parent, int index)
 {
     TextNote newNote = new TextNote();
     Application.Current.Dispatcher.Invoke(() =>
     {
         Xceed.Wpf.Toolkit.RichTextBox rtb = new Xceed.Wpf.Toolkit.RichTextBox();
         rtb.SelectAll();
         if (Settings.Default.UseDefaultFont && Settings.Default.DefaultFont != null)
         {
             rtb.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, (FontFamily)Settings.Default.DefaultFont);
             if (Settings.Default.DefaultFontSize > 0)
                 rtb.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, Settings.Default.DefaultFontSize);
         }
         else if (Settings.Default.MostRecentFont != null)
         {
             rtb.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, (FontFamily)Settings.Default.MostRecentFont);
             rtb.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, Settings.Default.MostRecentFontSize);
         }
         newNote.Rtf = rtb.Text;
     });
     AddNote(newNote, parent, index);
     return newNote;
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Exports text note elements.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="productWrapper">
        /// The ProductWrapper.
        /// </param>
        public static void Export(ExporterIFC exporterIFC, TextNote textNote, ProductWrapper productWrapper)
        {
            IFCFile file = exporterIFC.GetFile();
            using (IFCTransaction tr = new IFCTransaction(file))
            {
                string textString = textNote.Text;
                if (String.IsNullOrEmpty(textString))
                    throw new Exception("TextNote does not have test string.");

                ElementId symId = textNote.GetTypeId();
                if (symId == ElementId.InvalidElementId)
                    throw new Exception("TextNote does not have valid type id.");

                PresentationStyleAssignmentCache cache = ExporterCacheManager.PresentationStyleAssignmentCache;
                IFCAnyHandle presHnd = cache.Find(symId);
                if (IFCAnyHandleUtil.IsNullOrHasNoValue(presHnd))
                {
                    TextElementType textElemType = textNote.Symbol;
                    CreatePresentationStyleAssignmentForTextElementType(exporterIFC, textElemType, cache);
                    presHnd = cache.Find(symId);
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(presHnd))
                        throw new Exception("Failed to create presentation style assignment for TextElementType.");
                }

                HashSet<IFCAnyHandle> presHndSet = new HashSet<IFCAnyHandle>();
                presHndSet.Add(presHnd);

                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, textNote))
                {
                    const double planScale = 100.0;  // currently hardwired.

                    XYZ orig = UnitUtil.ScaleLength(textNote.Coord);
                    XYZ yDir = textNote.UpDirection;
                    XYZ xDir = textNote.BaseDirection;
                    XYZ zDir = xDir.CrossProduct(yDir);

                    double sizeX = UnitUtil.ScaleLength(textNote.Width * planScale);
                    double sizeY = UnitUtil.ScaleLength(textNote.Height * planScale);

                    // When we display text on screen, we "flip" it if the xDir is negative with relation to
                    // the X-axis.  So if it is, we'll flip x and y.
                    bool flipOrig = false;
                    if (xDir.X < 0)
                    {
                        xDir = xDir.Multiply(-1.0);
                        yDir = yDir.Multiply(-1.0);
                        flipOrig = true;
                    }

                    // xFactor, yFactor only used if flipOrig.
                    double xFactor = 0.0, yFactor = 0.0;
                    string boxAlignment = ConvertTextNoteAlignToBoxAlign(textNote, out xFactor, out yFactor);

                    // modify the origin to match the alignment.  In Revit, the origin is at the top-left (unless flipped,
                    // then bottom-right).
                    if (flipOrig)
                    {
                        orig = orig.Add(xDir.Multiply(sizeX * xFactor));
                        orig = orig.Add(yDir.Multiply(sizeY * yFactor));
                    }

                    IFCAnyHandle origin = ExporterUtil.CreateAxis(file, orig, zDir, xDir);

                    IFCAnyHandle extent = IFCInstanceExporter.CreatePlanarExtent(file, sizeX, sizeY);
                    IFCAnyHandle repItemHnd = IFCInstanceExporter.CreateTextLiteralWithExtent(file, textString, origin, Toolkit.IFCTextPath.Left, extent, boxAlignment);
                    IFCAnyHandle annoTextOccHnd = IFCInstanceExporter.CreateStyledItem(file, repItemHnd, presHndSet, null);

                    ElementId catId = textNote.Category != null ? textNote.Category.Id : ElementId.InvalidElementId;
                    HashSet<IFCAnyHandle> bodyItems = new HashSet<IFCAnyHandle>();
                    bodyItems.Add(repItemHnd);
                    IFCAnyHandle bodyRepHnd = RepresentationUtil.CreateAnnotationSetRep(exporterIFC, textNote, catId, exporterIFC.Get2DContextHandle(), bodyItems);

                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepHnd))
                        throw new Exception("Failed to create shape representation.");

                    IList<IFCAnyHandle> shapeReps = new List<IFCAnyHandle>();
                    shapeReps.Add(bodyRepHnd);

                    IFCAnyHandle prodShapeHnd = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);
                    IFCAnyHandle annoHnd = IFCInstanceExporter.CreateAnnotation(file, GUIDUtil.CreateGUID(), exporterIFC.GetOwnerHistoryHandle(),
                        null, null, null, setter.LocalPlacement, prodShapeHnd);

                    productWrapper.AddAnnotation(annoHnd, setter.LevelInfo, true);
                }

                tr.Commit();
            }
        }
Ejemplo n.º 31
0
        //Get the Selected Viewports from the linked model, check to see if the sheet they are on exists and if they are already placed.
        //If not, create and set the properties of both.
        private void btnOK_Click(object sender, EventArgs e)
        {
            int         itemCount     = 0;
            bool        TitleLocation = true;
            ElementId   typeId        = (ElementId)cbViewPortTypes.SelectedValue;
            ElementType vpType        = doc.GetElement(typeId) as ElementType;

            //Check to see if the Viewport Type has the Show Title property set to Yes, if it is not, we can't calculate its location
            //relative to the viewport to move it to the same location as the Linked Model
            if (vpType.LookupParameter("Show Title").AsInteger() != 1)
            {
                if (TaskDialog.Show("Viewport Show Title", "The Viewport Type selected does not have the 'Show Title' property set to Yes and the View placement may not be as expected.\nWould you like to continue?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.No) == TaskDialogResult.No)
                {
                    return;
                }
                else
                {
                    TitleLocation = false;
                }
            }

            //Use a Transaction Group for multiple transactions to be grouped as one. This enables the creation of sheets and views during the method
            //without throwing an exception that the elements don't exist
            using (TransactionGroup tGroup = new TransactionGroup(doc, "Create Linked Views"))
            {
                tGroup.Start();
                using (Transaction t = new Transaction(doc))
                {
                    ElementId vpTypeId = ((Element)cboTitleBlock.SelectedValue).Id;
                    foreach (DataGridViewRow row in dgvLinkedViews.SelectedRows)
                    {
                        //use a try block to make sure any errors don't crash revit
                        try
                        {
                            t.Start("Create View");
                            string         detailNumber   = (string)row.Cells[1].Value;
                            ViewFamilyType viewfamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.Drafting);
                            TextNoteType   textnoteType   = new FilteredElementCollector(doc).OfClass(typeof(TextNoteType)).Cast <TextNoteType>().FirstOrDefault();
                            ViewDrafting   draftingView   = ViewDrafting.Create(doc, viewfamilyType.Id);
                            draftingView.Name = (string)row.Cells[3].Value;
                            draftingView.LookupParameter("Title on Sheet").Set("REFERENCE VIEW - DO NOT PRINT");

                            //Set additional View Parameters based on Firm standards and Project Broswer Sorting templates
                            //if (dView.LookupParameter("Sheet Sort") is Parameter sSort)
                            //{
                            //    sSort.Set("PLANS");
                            //}

                            //Set the Linked View Yes/No Parameter to "Yes" for the Reload Function to Track
                            if (draftingView.LookupParameter("Linked View") is Parameter lView)
                            {
                                //Using 0 or 1 to set Yes (1) / No (0) parameters
                                lView.Set(1);
                            }
                            else
                            {
                                TaskDialog.Show("Missing Parameter", "Linked View Yes/No parameter is missing from View category and cannot continue.");
                                break;
                            }
                            //Set the Linked View GUID parameter to track the view in the Linked model
                            if (draftingView.LookupParameter("Linked View GUID") is Parameter lGUID)
                            {
                                lGUID.Set((string)row.Cells[5].Value);
                            }
                            else
                            {
                                TaskDialog.Show("Missing Parameter", "Linked View GUID Text parameter is missing from View category and cannot continue.");
                                break;
                            }
                            //Set the Link Name parameter to trak which Linked Model it came from.
                            if (draftingView.LookupParameter("Link Name") is Parameter lName)
                            {
                                lName.Set(cboLinks.Text);
                            }
                            else
                            {
                                TaskDialog.Show("Missing Parameter", "Link Name Text parameter is missing from View category and cannot continue.");
                                break;
                            }

                            //Creates one Text Note in the middle of the view to alert users that it is a Linked View and not to print it.
                            TextNote.Create(doc, draftingView.Id, new XYZ(0, 0, 0), "REFERENCE VIEW - DO NOT PRINT", textnoteType.Id);
                            t.Commit();

                            //Check to see if sheet with that number exits in the document
                            t.Start("Create Sheet");
                            ViewSheet sheet = CheckSheet((string)row.Cells[2].Value, vpTypeId);
                            t.Commit();

                            //Place the Drafting View reference on the sheet in the same location as in the Linked Model
                            t.Start("Place View");
                            if (sheet != null)
                            {
                                //Check to see if Viewport can be placed on sheet
                                if (Viewport.CanAddViewToSheet(doc, sheet.Id, draftingView.Id))
                                {
                                    if (CheckViewport(detailNumber, sheet))
                                    {
                                        XYZ      labelPoint = (XYZ)row.Cells[7].Value;
                                        Viewport vPort      = Viewport.Create(doc, sheet.Id, draftingView.Id, labelPoint);
                                        draftingView.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).Set(detailNumber);

                                        if (typeId != ElementId.InvalidElementId)
                                        {
                                            vPort.ChangeTypeId(typeId);
                                        }

                                        if (TitleLocation)
                                        {
                                            //Get the location of the Viewport and Viewport Label and Move the Viewport to match the Linked Document
                                            ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint - vPort.GetLabelOutline().MinimumPoint);
                                        }
                                        else
                                        {
                                            //If the Viewport Type does not have the Show Title property set to yes, we can't calculate the location
                                            //and we just place it int he location from the Linked model. This may not be the same location.
                                            ElementTransformUtils.MoveElement(doc, vPort.Id, labelPoint);
                                        }
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Existing Viewport", "Sheet " + sheet.SheetNumber + "-" + sheet.Name + " already contains a Viewport with Detail Number " + detailNumber + ", but detail " + draftingView.Name + " was created.");
                                    }
                                }
                            }
                            t.Commit();
                            itemCount++;
                        }
                        catch (Exception ex)
                        {
                            //This Exception will check if the View already exits in the project
                            if (ex.GetType() == typeof(Autodesk.Revit.Exceptions.ArgumentException))
                            {
                                TaskDialog.Show("Existing View", "View '" + (string)row.Cells[3].Value + "' already exists and will not be created.");
                                if (t.HasStarted())
                                {
                                    t.RollBack();
                                }
                                continue;
                            }
                            else
                            {
                                TaskDialog.Show("Error", ex.ToString());
                                //Check to see if a Transaction is active and roll it back if so
                                if (t.HasStarted())
                                {
                                    t.RollBack();
                                }
                                //check to see if the Group Transaction has started and roll it back if so
                                if (tGroup.HasStarted())
                                {
                                    tGroup.RollBack();
                                }
                            }
                        }
                    }
                }
                //Commit all of the changes from the Transaction group and other transactions
                tGroup.Assimilate();

                DialogResult = DialogResult.OK;
                Close();
            }
        }
Ejemplo n.º 32
0
        public override TextNote ConvertToTextNote()
        {
            TextNote newNote = new TextNote()
            {
                // default character names will normally be left alone, as they are highly descriptive;
                // they should probably be retained as explicit names after conversion
                ExplicitName = string.IsNullOrEmpty(this.ExplicitName) ? GetDefaultName() : this.ExplicitName,
                IsExpanded = this.IsExpanded,
                IsSelected = this.IsSelected
            };
            newNote.Ideas = Ideas;

            if (Relationship != null)
            {
                StringBuilder sb = new StringBuilder();
                if (Relationship != null)
                    sb.Append($"{Relationship.Name}: ");
                sb.Append(GetDefaultName());
                sb.Append($", {Genders.Name}");
                sb.AppendLine(AgeString);
                newNote.AddParagraph(sb.ToString());
            }
            newNote.AddParagraph(string.Empty);
            foreach (var line in Races.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Traits.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);
            newNote.AddParagraph(string.Empty);
            foreach (var line in Traits.GetSummary(0).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                newNote.AddParagraph(line);

            return newNote;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Converts text note align to box align.
        /// </summary>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="xFactor">
        /// The X factor.
        /// </param>
        /// <param name="yFactor">
        /// The Y factor.
        /// </param>
        static string ConvertTextNoteAlignToBoxAlign(TextNote textNote, out double xFactor, out double yFactor)
        {
            TextAlignFlags align = textNote.Align;

            int alignCase = 0;

            if ((align & TextAlignFlags.TEF_ALIGN_LEFT) != 0)
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 0;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 1;
                }
                else
                {
                    alignCase = 2;
                }
            }
            else if ((align & TextAlignFlags.TEF_ALIGN_RIGHT) != 0)
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 7;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 8;
                }
                else
                {
                    alignCase = 6;
                }
            }
            else
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 3;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 5;
                }
                else
                {
                    alignCase = 4;
                }
            }

            xFactor = 0.0;
            yFactor = 0.0;
            string boxAlignmeng = null;

            switch (alignCase)
            {
            case 0:
                boxAlignmeng = "top-left";
                xFactor      = -1.0;
                yFactor      = 1.0;
                break;

            case 1:
                boxAlignmeng = "bottom-left";
                xFactor      = -1.0;
                yFactor      = -1.0;
                break;

            case 2:
                boxAlignmeng = "middle-left";
                xFactor      = -1.0;
                break;

            case 3:
                boxAlignmeng = "top-middle";
                yFactor      = 1.0;
                break;

            case 4:
                boxAlignmeng = "center";
                break;

            case 5:
                boxAlignmeng = "bottom-middle";
                yFactor      = -1.0;
                break;

            case 6:
                boxAlignmeng = "middle-right";
                xFactor      = 1.0;
                break;

            case 7:
                boxAlignmeng = "top-right";
                xFactor      = 1.0;
                yFactor      = 1.0;
                break;

            case 8:
                boxAlignmeng = "bottom-right";
                xFactor      = 1.0;
                yFactor      = -1.0;
                break;
            }

            return(boxAlignmeng);
        }
Ejemplo n.º 34
0
 private TextNote LoadTextNote(string path, IdeaNote parent, int index)
 {
     TextNote newNote = new TextNote();
     AddNote(newNote, parent, index);
     string text;
     try { text = File.ReadAllText(path); }
     catch (Exception) { return newNote; } // failures allowed to pass without mention; expected to be obvious without intrusive dialog warning
     if (Path.GetExtension(path).ToLowerInvariant() == ".rtf") newNote.Rtf = text;
     else newNote.SetRtfFromPlainText(text);
     return newNote;
 }
Ejemplo n.º 35
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            try
            {
                XYZ origin = uidoc.Selection.PickPoint("Select insertion point");

                double width = 0.2; //feet

                Category c = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);

                CategoryNameMap subcats = c.SubCategories;

                double offset = 0;

                TextNoteOptions options = new TextNoteOptions();
                options.HorizontalAlignment = HorizontalTextAlignment.Left;
                options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

                var dict = new SortedDictionary <string, GraphicsStyle>();

                foreach (Category lineStyle in subcats)
                {
                    GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection);

                    dict.Add(gs.Name, gs);
                }


                var output = dict.OrderBy(e => e.Key).Select(e => new { graphicStyle = e.Value, linestyleName = e.Key }).ToList();


                using (Transaction t = new Transaction(doc, "Place Lines"))
                {
                    t.Start();

                    //foreach( Line item in ordered) {
                    foreach (var item in output)
                    {
                        //					GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection);

                        XYZ newOrigin   = new XYZ(origin.X, origin.Y + offset, 0);
                        XYZ offsetPoint = new XYZ(origin.X + width, origin.Y + offset, 0);

                        Line L1 = Line.CreateBound(newOrigin, offsetPoint);

                        try
                        {
                            TextNote note = TextNote.Create(doc, doc.ActiveView.Id, new XYZ(origin.X - 0.2, origin.Y + offset + 0.01, 0), 0.2, item.linestyleName, options);

                            DetailCurve e = doc.Create.NewDetailCurve(doc.ActiveView, L1);

                            Parameter p = e.LookupParameter("Line Style");

                            p.Set(item.graphicStyle.Id);
                        }
                        catch
                        {
                        }
                        offset -= 0.03;
                    }

                    t.Commit();
                }


                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
        /// <summary>
        /// Converts text note align to box align.
        /// </summary>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="xFactor">
        /// The X factor.
        /// </param>
        /// <param name="yFactor">
        /// The Y factor.
        /// </param>
        static string ConvertTextNoteAlignToBoxAlign(TextNote textNote, out double xFactor, out double yFactor)
        {
            TextAlignFlags align = textNote.Align;

            int alignCase = 0;

            if ((align & TextAlignFlags.TEF_ALIGN_LEFT) != 0)
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 0;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 1;
                }
                else
                {
                    alignCase = 2;
                }
            }
            else if ((align & TextAlignFlags.TEF_ALIGN_RIGHT) != 0)
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 7;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 8;
                }
                else
                {
                    alignCase = 6;
                }
            }
            else
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 3;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 5;
                }
                else
                {
                    alignCase = 4;
                }
            }

            xFactor = 0.0;
            yFactor = 0.0;
            string boxAlignmeng = null;

            switch (alignCase)
            {
                case 0:
                    boxAlignmeng = "top-left";
                    xFactor = -1.0;
                    yFactor = 1.0;
                    break;
                case 1:
                    boxAlignmeng = "bottom-left";
                    xFactor = -1.0;
                    yFactor = -1.0;
                    break;
                case 2:
                    boxAlignmeng = "middle-left";
                    xFactor = -1.0;
                    break;
                case 3:
                    boxAlignmeng = "top-middle";
                    yFactor = 1.0;
                    break;
                case 4:
                    boxAlignmeng = "center";
                    break;
                case 5:
                    boxAlignmeng = "bottom-middle";
                    yFactor = -1.0;
                    break;
                case 6:
                    boxAlignmeng = "middle-right";
                    xFactor = 1.0;
                    break;
                case 7:
                    boxAlignmeng = "top-right";
                    xFactor = 1.0;
                    yFactor = 1.0;
                    break;
                case 8:
                    boxAlignmeng = "bottom-right";
                    xFactor = 1.0;
                    yFactor = -1.0;
                    break;
            }

            return boxAlignmeng;
        }
Ejemplo n.º 37
0
        public static void Place(UIApplication uiapp, TextLeaderPosition _textLeader, double _textWidth, double _leaderLength)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            IList <UIView> uiviews = uidoc.GetOpenUIViews();
            UIView         uiview  = null;

            foreach (UIView uv in uiviews)
            {
                if (uv.ViewId.Equals(doc.ActiveView.Id))
                {
                    uiview = uv;
                    break;
                }
            }


            IList <XYZ> corners = uiview.GetZoomCorners();
            XYZ         p       = corners[0];
            XYZ         q       = corners[1];
            XYZ         v       = q - p;
            XYZ         center  = p + 0.5 * v;

            try
            {
                using (Transaction tran = new Transaction(doc, "Text note created"))
                {
                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
                    {
                        //uses PresentationCore
                        string textNoteContent = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

                        //double width = 3.0 / 12.0; // feet on paper

                        TextNoteOptions options = new TextNoteOptions();
                        options.HorizontalAlignment = HorizontalTextAlignment.Left;

                        options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
                        double noteWidth = _textWidth / 12;

                        tran.Start();
                        TextNote note = TextNote.Create(doc, doc.ActiveView.Id, center, textNoteContent, options);
                        note.Width = noteWidth;



                        if (_textLeader == TextLeaderPosition.Both)
                        {
                            note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                            Leader lead = note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                            note.LeaderLeftAttachment  = LeaderAtachement.TopLine;
                            note.LeaderRightAttachment = LeaderAtachement.TopLine;
                            note.Width = noteWidth;

                            lead.End = new XYZ(center.X + _leaderLength, center.Y - 0.8, center.Z);
                        }
                        else if (_textLeader == TextLeaderPosition.Left)
                        {
                            note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                            note.LeaderLeftAttachment = LeaderAtachement.TopLine;
                            note.Width = noteWidth;
                        }
                        else if (_textLeader == TextLeaderPosition.Right)
                        {
                            Leader lead = note.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                            note.LeaderRightAttachment = LeaderAtachement.TopLine;
                            note.Width = noteWidth;


                            //lead.Elbow = new XYZ(center.X, center.Y, center.Z);

                            lead.End = new XYZ(center.X + _leaderLength, center.Y - 0.8, center.Z);
                        }

                        tran.Commit();
                    }
                    else
                    {
                        TaskDialog.Show("Warning", "Clipboard is empty. Try to copy something.");
                    }
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
        }
        /// <summary>
        /// Converts text note align to box align.
        /// </summary>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="xFactor">
        /// The X factor.
        /// </param>
        /// <param name="yFactor">
        /// The Y factor.
        /// </param>
        static IFCLabel ConvertTextNoteAlignToBoxAlign(TextNote textNote, out double xFactor, out double yFactor)
        {
            TextAlignFlags align = textNote.Align;

            int alignCase = 0;

            if ((align & TextAlignFlags.TEF_ALIGN_LEFT) != 0)
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 0;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 1;
                }
                else
                {
                    alignCase = 2;
                }
            }
            else if ((align & TextAlignFlags.TEF_ALIGN_RIGHT) != 0)
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 7;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 8;
                }
                else
                {
                    alignCase = 6;
                }
            }
            else
            {
                if ((align & TextAlignFlags.TEF_ALIGN_TOP) != 0)
                {
                    alignCase = 3;
                }
                else if ((align & TextAlignFlags.TEF_ALIGN_BOTTOM) != 0)
                {
                    alignCase = 5;
                }
                else
                {
                    alignCase = 4;
                }
            }

            xFactor = 0.0;
            yFactor = 0.0;
            IFCLabel alignLabel = IFCLabel.Create();

            switch (alignCase)
            {
                case 0:
                    alignLabel = IFCLabel.Create("top-left");
                    xFactor = -1.0;
                    yFactor = 1.0;
                    break;
                case 1:
                    alignLabel = IFCLabel.Create("bottom-left");
                    xFactor = -1.0;
                    yFactor = -1.0;
                    break;
                case 2:
                    alignLabel = IFCLabel.Create("middle-left");
                    xFactor = -1.0;
                    break;
                case 3:
                    alignLabel = IFCLabel.Create("top-middle");
                    yFactor = 1.0;
                    break;
                case 4:
                    alignLabel = IFCLabel.Create("center");
                    break;
                case 5:
                    alignLabel = IFCLabel.Create("bottom-middle");
                    yFactor = -1.0;
                    break;
                case 6:
                    alignLabel = IFCLabel.Create("middle-right");
                    xFactor = 1.0;
                    break;
                case 7:
                    alignLabel = IFCLabel.Create("top-right");
                    xFactor = 1.0;
                    yFactor = 1.0;
                    break;
                case 8:
                    alignLabel = IFCLabel.Create("bottom-right");
                    xFactor = 1.0;
                    yFactor = -1.0;
                    break;
            }

            return alignLabel;
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Exports text note elements.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="productWrapper">
        /// The ProductWrapper.
        /// </param>
        public static void Export(ExporterIFC exporterIFC, TextNote textNote, ProductWrapper productWrapper)
        {
            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            string            predefinedType = null;
            IFCExportInfoPair exportType     = ExporterUtil.GetProductExportType(exporterIFC, textNote, out predefinedType);

            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(exportType.ExportInstance))
            {
                return;
            }

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                string textString = textNote.Text;
                if (String.IsNullOrEmpty(textString))
                {
                    throw new Exception("TextNote does not have test string.");
                }

                ElementId symId = textNote.GetTypeId();
                if (symId == ElementId.InvalidElementId)
                {
                    throw new Exception("TextNote does not have valid type id.");
                }

                PresentationStyleAssignmentCache cache = ExporterCacheManager.PresentationStyleAssignmentCache;
                IFCAnyHandle presHnd = cache.Find(symId);
                if (IFCAnyHandleUtil.IsNullOrHasNoValue(presHnd))
                {
                    TextElementType textElemType = textNote.Symbol;
                    CreatePresentationStyleAssignmentForTextElementType(exporterIFC, textElemType, cache);
                    presHnd = cache.Find(symId);
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(presHnd))
                    {
                        throw new Exception("Failed to create presentation style assignment for TextElementType.");
                    }
                }

                HashSet <IFCAnyHandle> presHndSet = new HashSet <IFCAnyHandle>();
                presHndSet.Add(presHnd);

                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, textNote))
                {
                    const double planScale = 100.0; // currently hardwired.

                    XYZ orig = UnitUtil.ScaleLength(textNote.Coord);
                    XYZ yDir = textNote.UpDirection;
                    XYZ xDir = textNote.BaseDirection;
                    XYZ zDir = xDir.CrossProduct(yDir);

                    double sizeX = UnitUtil.ScaleLength(textNote.Width * planScale);
                    double sizeY = UnitUtil.ScaleLength(textNote.Height * planScale);

                    // When we display text on screen, we "flip" it if the xDir is negative with relation to
                    // the X-axis.  So if it is, we'll flip x and y.
                    bool flipOrig = false;
                    if (xDir.X < 0)
                    {
                        xDir     = xDir.Multiply(-1.0);
                        yDir     = yDir.Multiply(-1.0);
                        flipOrig = true;
                    }

                    // xFactor, yFactor only used if flipOrig.
                    double xFactor = 0.0, yFactor = 0.0;
                    string boxAlignment = ConvertTextNoteAlignToBoxAlign(textNote, out xFactor, out yFactor);

                    // modify the origin to match the alignment.  In Revit, the origin is at the top-left (unless flipped,
                    // then bottom-right).
                    if (flipOrig)
                    {
                        orig = orig.Add(xDir.Multiply(sizeX * xFactor));
                        orig = orig.Add(yDir.Multiply(sizeY * yFactor));
                    }

                    IFCAnyHandle origin = ExporterUtil.CreateAxis(file, orig, zDir, xDir);

                    IFCAnyHandle extent         = IFCInstanceExporter.CreatePlanarExtent(file, sizeX, sizeY);
                    IFCAnyHandle repItemHnd     = IFCInstanceExporter.CreateTextLiteralWithExtent(file, textString, origin, Toolkit.IFCTextPath.Left, extent, boxAlignment);
                    IFCAnyHandle annoTextOccHnd = IFCInstanceExporter.CreateStyledItem(file, repItemHnd, presHndSet, null);

                    ElementId catId = textNote.Category != null ? textNote.Category.Id : ElementId.InvalidElementId;
                    HashSet <IFCAnyHandle> bodyItems = new HashSet <IFCAnyHandle>();
                    bodyItems.Add(repItemHnd);
                    IFCAnyHandle bodyRepHnd = RepresentationUtil.CreateAnnotationSetRep(exporterIFC, textNote, catId, exporterIFC.Get2DContextHandle(), bodyItems);

                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepHnd))
                    {
                        throw new Exception("Failed to create shape representation.");
                    }

                    IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>();
                    shapeReps.Add(bodyRepHnd);

                    IFCAnyHandle prodShapeHnd = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);
                    IFCAnyHandle instHnd;
                    if (exportType.ExportInstance == Common.Enums.IFCEntityType.IfcAnnotation)
                    {
                        instHnd = IFCInstanceExporter.CreateAnnotation(exporterIFC, textNote, GUIDUtil.CreateGUID(), ExporterCacheManager.OwnerHistoryHandle,
                                                                       setter.LocalPlacement, prodShapeHnd);
                    }
                    else
                    {
                        instHnd = IFCInstanceExporter.CreateGenericIFCEntity(exportType, exporterIFC, textNote, GUIDUtil.CreateGUID(), ExporterCacheManager.OwnerHistoryHandle,
                                                                             setter.LocalPlacement, prodShapeHnd);
                    }

                    productWrapper.AddAnnotation(instHnd, setter.LevelInfo, true);
                }

                tr.Commit();
            }
        }
        /// <summary>
        /// Exports text note elements.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="productWrapper">
        /// The IFCProductWrapper.
        /// </param>
        public static void Export(ExporterIFC exporterIFC, TextNote textNote, IFCProductWrapper productWrapper, PresentationStyleAssignmentCache cache)
        {
            IFCFile file = exporterIFC.GetFile();
            using (IFCTransaction tr = new IFCTransaction(file))
            {
                string textString = textNote.Text;
                if (String.IsNullOrEmpty(textString))
                    throw new Exception("TextNote does not have test string.");

                ElementId symId = textNote.GetTypeId();
                if (symId == ElementId.InvalidElementId)
                    throw new Exception("TextNote does not have valid type id.");

                IFCAnyHandle presHnd = cache.Find(symId);
                if (!presHnd.HasValue)
                {
                    TextElementType textElemType = textNote.Symbol;
                    CreatePresentationStyleAssignmentForTextElementType(exporterIFC, textElemType, cache);
                    presHnd = cache.Find(symId);
                    if (!presHnd.HasValue)
                        throw new Exception("Failed to create presentation style assignment for TextElementType.");
                }

                IList<IFCAnyHandle> presHndSet = new List<IFCAnyHandle>();
                presHndSet.Add(presHnd);

                using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, textNote))
                {
                    double linScale = exporterIFC.LinearScale;
                    const double planScale = 100.0;  // currently hardwired.

                    XYZ orig = textNote.Coord;
                    orig = orig.Multiply(linScale);
                    XYZ yDir = textNote.UpDirection;
                    XYZ xDirection = textNote.BaseDirection;
                    XYZ zDirection = xDirection.CrossProduct(yDir);

                    double sizeX = textNote.LineWidth * linScale * planScale;
                    double sizeY = textNote.Height * linScale * planScale;

                    // When we display text on screen, we "flip" it if the xDirection is negative with relation to
                    // the X-axis.  So if it is, we'll flip x and y.
                    bool flipOrig = false;
                    if (xDirection.X < 0)
                    {
                        xDirection = xDirection.Multiply(-1.0);
                        yDir = yDir.Multiply(-1.0);
                        flipOrig = true;
                    }

                    // xFactor, yFactor only used if flipOrig.
                    double xFactor = 0.0, yFactor = 0.0;
                    IFCLabel boxAlign = ConvertTextNoteAlignToBoxAlign(textNote, out xFactor, out yFactor);

                    // modify the origin to match the alignment.  In Revit, the origin is at the top-left (unless flipped,
                    // then bottom-right).
                    if (flipOrig)
                    {
                        orig = orig.Add(xDirection.Multiply(sizeX * xFactor));
                        orig = orig.Add(yDir.Multiply(sizeY * yFactor));
                    }

                    IFCAnyHandle origin = ExporterUtil.CreateAxis(file, orig, zDirection, xDirection);

                    IFCLabel textStringLabel = IFCLabel.Create(textString);
                    IFCAnyHandle extent = file.CreatePlanarExtent(sizeX, sizeY);
                    IFCAnyHandle repItemHnd = file.CreateTextLiteralWithExtent(textStringLabel, origin, IFCTextPath.Left, extent, boxAlign);
                    IFCAnyHandle annoTextOccHnd = file.CreateStyledItem(repItemHnd, presHndSet, IFCLabel.Create());

                    ElementId catId = textNote.Category != null ? textNote.Category.Id : ElementId.InvalidElementId;
                    IFCLabel identifierOpt = IFCLabel.Create("Annotation");
                    IFCLabel repTypeOpt = IFCLabel.Create("Annotation2D");	// this is by IFC2x3 convention, not temporary
                    HashSet<IFCAnyHandle> bodyItems = new HashSet<IFCAnyHandle>();
                    bodyItems.Add(repItemHnd);
                    IFCAnyHandle bodyRepHnd = RepresentationUtil.CreateShapeRepresentation(exporterIFC, catId, exporterIFC.Get2DContextHandle(), identifierOpt, repTypeOpt, bodyItems);

                    if (!bodyRepHnd.HasValue)
                        throw new Exception("Failed to create shape representation.");

                    IList<IFCAnyHandle> shapeReps = new List<IFCAnyHandle>();
                    shapeReps.Add(bodyRepHnd);

                    IFCAnyHandle prodShapeHnd = file.CreateProductDefinitionShape(IFCLabel.Create(), IFCLabel.Create(), shapeReps);
                    IFCAnyHandle annoHnd = file.CreateAnnotation(IFCLabel.CreateGUID(), exporterIFC.GetOwnerHistoryHandle(),
                        IFCLabel.Create(), IFCLabel.Create(), IFCLabel.Create(), setter.GetPlacement(), prodShapeHnd);

                    productWrapper.AddAnnotation(annoHnd, setter.GetLevelInfo(), true);
                }

                tr.Commit();
            }
        }
Ejemplo n.º 41
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // get view types
            FilteredElementCollector viewCol
                = new FilteredElementCollector(doc)
                  .WhereElementIsElementType()
                  .OfClass(typeof(ViewFamilyType));

            ViewFamilyType viewFamilyTypeFP = null;
            ViewFamilyType viewFamilyTypeS  = null;
            ViewFamilyType viewFamilyTypeD  = null;

            foreach (ViewFamilyType view in viewCol)
            {
                if (view.ViewFamily == ViewFamily.FloorPlan)
                {
                    viewFamilyTypeFP = view;
                }
                if (view.ViewFamily == ViewFamily.Section)
                {
                    viewFamilyTypeS = view;
                }
                if (view.ViewFamily == ViewFamily.Detail)
                {
                    viewFamilyTypeD = view;
                }
            }

            // collecting categories which must be visible (structural stiffener, structural column and text note
            List <ElementId> categoriesToShow = new List <ElementId>();

            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_StructuralStiffener)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_StructuralColumns)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_TextNotes)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_Dimensions)
                                 .ToElements()
                                 .First().Category.Id);

            // declaring elementsCol and elementsToHide variables
            Categories categories = doc.Settings.Categories;
            TextNote   textNote;
            Leader     leader;
            ElementId  defaultTextNoteTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);


            // retrieve elements from database
            FilteredElementCollector col
                = new FilteredElementCollector(doc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_StructuralStiffener);

            // create a list to save the types already handled
            List <string> typesHandled = new List <string>();

            // modify document within a transaction
            using (Transaction tx = new Transaction(doc))
            {
                bool warningKey = true;
                tx.Start("Criar detalhe das chapas");
                // get first element for tests
                foreach (Element e in col)
                {
                    // handling plate type with comment
                    Parameter commentParam = e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);

                    // checking comment param
                    if (commentParam.AsString() == null)
                    {
                        if (warningKey)
                        {
                            System.Windows.Forms.MessageBox.Show("Foi encontrada uma chapa sem indicação de tipo, " +
                                                                 "ela será ignorada pelo add-in.", "Aviso");
                            warningKey = false;
                        }
                        continue;
                    }

                    string[] splittedParam = (from str in commentParam.AsString().Split(_Separators)
                                              select str.ToLower())
                                             .ToArray();

                    int plateType = 0;
                    try
                    {
                        plateType = int.Parse(splittedParam.Last().Split(' ').Last());
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("Problemas ao identificar o tipo da chapa. " +
                                                             splittedParam.Last(), "Erro");
                        tx.RollBack();
                        return(Result.Failed);
                    }

                    if (typesHandled.ToArray().Intersect(splittedParam).Any())
                    {
                        continue;
                    }

                    List <View> existingViews = new List <View>();
                    if (!CheckNameAvailability(doc, plateType, ref existingViews))
                    {
                        switch (AskOverwriteDetailView(plateType))
                        {
                        case System.Windows.Forms.DialogResult.Yes:
                            doc.Delete((from view in existingViews select view.Id).ToList());
                            break;

                        case System.Windows.Forms.DialogResult.No:
                            tx.RollBack();
                            return(Result.Cancelled);

                        case System.Windows.Forms.DialogResult.Cancel:
                            tx.RollBack();
                            return(Result.Cancelled);
                        }
                    }

                    // get boundingbox of element
                    BoundingBoxXYZ ebbox = e.get_BoundingBox(null);
                    double         w     = ebbox.Max.X - ebbox.Min.X;
                    double         d     = ebbox.Max.Y - ebbox.Min.Y;
                    double         h     = ebbox.Max.Z - ebbox.Min.Z;

                    // creating boundingbox for vertical view section
                    BoundingBoxXYZ vBbox = new BoundingBoxXYZ();
                    vBbox.Enabled = true;
                    vBbox.Max     = new XYZ(w + 0.2, h + 2, d + 0.2);
                    vBbox.Min     = new XYZ(-w - 0.2, -h - 0.2, -d - 0.2);

                    // creating boundingbox for horizontal view section
                    BoundingBoxXYZ hBbox = new BoundingBoxXYZ();
                    hBbox.Enabled = true;
                    hBbox.Max     = new XYZ(w + 0.2, d + 0.2, h + 0.2);
                    hBbox.Min     = new XYZ(-w - 0.2, -d - 0.2, -h - 0.2);

                    // set the transform
                    Transform vTrans = Transform.Identity;
                    Transform hTrans = Transform.Identity;

                    // find the element mid point
                    XYZ midPt = 0.5 * (ebbox.Max + ebbox.Min);

                    // set it as origin
                    vTrans.Origin = midPt;
                    hTrans.Origin = midPt;

                    // determine view direction for vView
                    vTrans.BasisX = XYZ.BasisX;
                    vTrans.BasisY = XYZ.BasisZ;
                    vTrans.BasisZ = -XYZ.BasisY;

                    // determine view direction for hView
                    hTrans.BasisX = -XYZ.BasisX;
                    hTrans.BasisY = XYZ.BasisY;
                    hTrans.BasisZ = -XYZ.BasisZ;

                    // transforming
                    vBbox.Transform = vTrans;
                    hBbox.Transform = hTrans;

                    // creating vertical view section
                    ViewSection vView = ViewSection.CreateDetail(doc, viewFamilyTypeD.Id, vBbox);

                    // hidding categories in vertical view section
                    foreach (Category category in categories)
                    {
                        if (!categoriesToShow.Contains(category.Id) &&
                            vView.CanCategoryBeHidden(category.Id))
                        {
                            vView.SetCategoryHidden(category.Id, true);
                        }
                    }

                    // scale
                    int scaleValue = 20;

                    // configuring vertical view properties
                    vView.Name           = MakeViewNames(plateType)[0];
                    vView.DetailLevel    = ViewDetailLevel.Fine;
                    vView.DisplayStyle   = DisplayStyle.FlatColors;
                    vView.CropBoxVisible = false;
                    vView.Scale          = scaleValue;

                    // creating textNotes
                    String text0 = "LIGAÇÃO COLUNA X CHAPA \nFEITA ATRAVÉS DE SOLDA";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text0, defaultTextNoteTypeId);
                    //leader = textNote.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                    //leader.End = vBbox.Transform.Origin + new XYZ(0, -5, 0);

                    String text1 = "CHUMBAR CHAPA COM ADESIVO \nEPOXI SIKADUR 32 OU SIMILAR" +
                                   "\nVERIFICAR MODO DE UTILIZAÇÃO \nJUNTO AO FORNECEDOR";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text1, defaultTextNoteTypeId);
                    //leader = textNote.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                    //leader.End = vBbox.Transform.Origin + new XYZ(0, -50, 0);

                    String text2 = "PREENCHER COM EPS";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text2, defaultTextNoteTypeId);

                    String text3 = "CHUMBAR CHAPA \nCOM ADESIVO EPOXI";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text3, defaultTextNoteTypeId);

                    // creating horizontal view section
                    ViewSection hView = ViewSection.CreateDetail(doc, viewFamilyTypeD.Id, hBbox);

                    // hidding categories in horizontal view section
                    foreach (Category category in categories)
                    {
                        if (!categoriesToShow.Contains(category.Id) &&
                            hView.CanCategoryBeHidden(category.Id))
                        {
                            hView.SetCategoryHidden(category.Id, true);
                        }
                    }

                    // configuring hView properties
                    hView.Name           = MakeViewNames(plateType)[1];
                    hView.DetailLevel    = ViewDetailLevel.Fine;
                    hView.DisplayStyle   = DisplayStyle.HLR;
                    hView.CropBoxVisible = false;
                    hView.Scale          = scaleValue;

                    // adding type handled to list
                    typesHandled.Add(String.Format("tipo {0}", (plateType).ToString()));
                }
                tx.Commit();
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 42
0
        private void Stream( ArrayList data, TextNote textNote )
        {
            data.Add( new Snoop.Data.ClassSeparator( typeof( TextNote ) ) );

              data.Add( new Snoop.Data.Xyz( "Coord", textNote.Coord ) );
              data.Add( new Snoop.Data.Enumerable( "Leaders", textNote.GetLeaders() ) );
              data.Add( new Snoop.Data.Double( "Width", textNote.Width ) );
              data.Add( new Snoop.Data.Object( "Text note type", textNote.TextNoteType ) );
        }
        /// <summary>
        /// Converts text note align to box align.
        /// </summary>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="xFactor">
        /// The X factor.
        /// </param>
        /// <param name="yFactor">
        /// The Y factor.
        /// </param>
        static string ConvertTextNoteAlignToBoxAlign(TextNote textNote, out double xFactor, out double yFactor)
        {
            xFactor = yFactor = 0.0;

            // boxAlignment consist of a combination of vertical and horizontal alignment
            // except for the middle-middle alignment which is named simply "center"
            // The xFactor and yFactor are set as follows:
            //      +1
            //   -1  0  +1
            //      -1

            // The center-middle is an odd case; we can deal with it firs

            if(   (HorizontalTextAlignment.Center == textNote.HorizontalAlignment)
               && (VerticalTextAlignment.Middle == textNote.VerticalAlignment) )
            {
               return "center";
            }

            string boxAlignment = null;

            switch(textNote.VerticalAlignment)
            {
               case VerticalTextAlignment.Top:
                  yFactor = 1.0;
                  boxAlignment = "top-";
                  break;
               case VerticalTextAlignment.Middle:
                     boxAlignment = "middle-";
                  break;
               case VerticalTextAlignment.Bottom:
                  yFactor = -1.0;
                  boxAlignment = "bottom-";
                  break;
            }

            switch(textNote.HorizontalAlignment)
            {
               case HorizontalTextAlignment.Left:
                  xFactor = -1.0;
                  boxAlignment += "left";
                  break;
               case HorizontalTextAlignment.Center:
                  boxAlignment += "middle";
                  break;
               case HorizontalTextAlignment.Right:
                  xFactor = 1.0;
                  boxAlignment += "right";
                  break;
            }

            return boxAlignment;
        }
Ejemplo n.º 44
0
        /// <summary>
        /// gets the actual score from a textnote
        /// </summary>
        /// <param name="note"></param>
        /// <param name="preText"></param>
        /// <returns></returns>
        private int GetScore(TextNote note, string preText)
        {
            string scoreOnly = note.Text.Replace(preText, "");

            int score;
            if (int.TryParse(scoreOnly, out score))
            {
                return score;
            }
            else
            {
                TaskDialog.Show("Scoring error", "The score tallies are corrupt, please reset the scores");
                return 0;
            }
        }