IMember GetMemberToDocument()
        {
            var   parsedDocument = ProjectDomService.Parse(Document.Project, Document.FileName, Document.Editor.Document.Text);
            IType type           = parsedDocument.CompilationUnit.GetTypeAt(textEditorData.Caret.Line, textEditorData.Caret.Column);

            if (type == null)
            {
                foreach (var t in parsedDocument.CompilationUnit.Types)
                {
                    if (t.Location.Line > textEditorData.Caret.Line)
                    {
                        return(t);
                    }
                }
                return(null);
            }

            IMember result = null;

            foreach (IMember member in type.Members)
            {
                if (member.Location > new DomLocation(textEditorData.Caret.Line, textEditorData.Caret.Column) && (result == null || member.Location < result.Location) && IsEmptyBetweenLines(textEditorData.Caret.Line, member.Location.Line))
                {
                    result = member;
                }
            }
            return(result);
        }
Esempio n. 2
0
        void StartReparseThread()
        {
            // Don't directly parse the document because doing it at every key press is
            // very inefficient. Do it after a small delay instead, so several changes can
            // be parsed at the same time.
            string currentParseFile = FileName;

            if (parseTimeout != 0)
            {
                GLib.Source.Remove(parseTimeout);
            }
            parseTimeout = GLib.Timeout.Add(ParseDelay, delegate {
                string currentParseText    = Editor.Text;
                Project curentParseProject = Project;
                // parser revice queue takes care of the locking
                ProjectDomService.QueueParseJob(dom, delegate(string name, IProgressMonitor monitor) {
                    var currentParsedDocument = ProjectDomService.Parse(curentParseProject, currentParseFile, currentParseText);
                    Application.Invoke(delegate {
                        this.parsedDocument = currentParsedDocument;
                        if (this.parsedDocument != null && !this.parsedDocument.HasErrors)
                        {
                            this.lastErrorFreeParsedDocument = parsedDocument;
                        }
                        OnDocumentParsed(EventArgs.Empty);
                    });
                }, FileName);
                parseTimeout = 0;
                return(false);
            });
        }
Esempio n. 3
0
        void ReplaceFile(string targetRelativePath, string sourceRelativePath)
        {
            string tfile = mainProject.Project.GetAbsoluteChildPath(targetRelativePath);
            string sfile = mainProject.Project.GetAbsoluteChildPath(sourceRelativePath);

            File.Copy(sfile, tfile, true);
            ProjectDomService.Parse(tfile, null);
        }
        internal static IParameterDataProvider CreateProvider(string text)
        {
            string parsedText;
            string editorText;
            int    cursorPosition = text.IndexOf('$');
            int    endPos         = text.IndexOf('$', cursorPosition + 1);

            if (endPos == -1)
            {
                parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1);
            }
            else
            {
                parsedText     = text.Substring(0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring(endPos + 1);
                editorText     = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1);
                cursorPosition = endPos - 1;
            }

            TestWorkbenchWindow tww     = new TestWorkbenchWindow();
            TestViewContent     sev     = new TestViewContent();
            DotNetProject       project = new DotNetAssemblyProject("C#");

            project.FileName = GetTempFile(".csproj");

            string file = GetTempFile(".cs");

            project.AddFile(file);

            ProjectDomService.Load(project);
//			ProjectDom dom = ProjectDomService.GetProjectDom (project);
            ProjectDomService.Parse(project, file, null, delegate { return(parsedText); });
            ProjectDomService.Parse(project, file, null, delegate { return(parsedText); });

            sev.Project        = project;
            sev.ContentName    = file;
            sev.Text           = editorText;
            sev.CursorPosition = cursorPosition;
            tww.ViewContent    = sev;
            Document doc = new Document(tww);

            doc.ParsedDocument = new NRefactoryParser().Parse(null, sev.ContentName, parsedText);
            CSharpTextEditorCompletion textEditorCompletion = new CSharpTextEditorCompletion(doc);

            CodeCompletionContext ctx = new CodeCompletionContext();

            ctx.TriggerOffset = sev.CursorPosition;
            int line, column;

            sev.GetLineColumnFromPosition(sev.CursorPosition, out line, out column);
            ctx.TriggerLine       = line;
            ctx.TriggerLineOffset = column;

            IParameterDataProvider result = textEditorCompletion.HandleParameterCompletion(ctx, editorText[cursorPosition - 1]);

            ProjectDomService.Unload(project);
            return(result);
        }
Esempio n. 5
0
        void OnClosed(object s, EventArgs a)
        {
            ProjectDomService.DomRegistered -= UpdateRegisteredDom;
            if (parseTimeout != 0)
            {
                GLib.Source.Remove(parseTimeout);
                parseTimeout = 0;
            }
            ClearTasks();

            string  currentParseFile   = FileName;
            Project curentParseProject = Project;

            if (window is SdiWorkspaceWindow)
            {
                ((SdiWorkspaceWindow)window).DetachFromPathedDocument();
            }
            window.Closed -= OnClosed;
            window.ActiveViewContentChanged -= OnActiveViewContentChanged;
            if (IdeApp.Workspace != null)
            {
                IdeApp.Workspace.ItemRemovedFromSolution -= OnEntryRemoved;
            }

            try {
                OnClosed(a);
            } catch (Exception ex) {
                LoggingService.LogError("Exception while calling OnClosed.", ex);
            }

            while (editorExtension != null)
            {
                try {
                    editorExtension.Dispose();
                } catch (Exception ex) {
                    LoggingService.LogError("Exception while disposing extension:" + editorExtension, ex);
                }
                editorExtension = editorExtension.Next as TextEditorExtension;
            }

            // Parse the file when the document is closed. In this way if the document
            // is closed without saving the changes, the saved compilation unit
            // information will be restored
            if (currentParseFile != null)
            {
                ProjectDomService.QueueParseJob(dom, delegate(string name, IProgressMonitor monitor) {
                    ProjectDomService.Parse(curentParseProject, currentParseFile);
                }, FileName);
            }
            if (isFileDom)
            {
                ProjectDomService.RemoveFileDom(FileName);
                dom = null;
            }

            Counters.OpenDocuments--;
        }
Esempio n. 6
0
        void OnClosed(object s, EventArgs a)
        {
            closed = true;
            ClearTasks();

            string  currentParseFile   = FileName;
            Project curentParseProject = Project;

            if (window is SdiWorkspaceWindow)
            {
                ((SdiWorkspaceWindow)window).DetachFromPathedDocument();
            }
            window.Closed -= OnClosed;
            window.ActiveViewContentChanged -= OnActiveViewContentChanged;
            if (IdeApp.Workspace != null)
            {
                IdeApp.Workspace.ItemRemovedFromSolution -= OnEntryRemoved;
            }

            try {
                OnClosed(a);
            } catch (Exception ex) {
                LoggingService.LogError("Exception while calling OnClosed.", ex);
            }

            while (editorExtension != null)
            {
                try {
                    editorExtension.Dispose();
                } catch (Exception ex) {
                    LoggingService.LogError("Exception while disposing extension:" + editorExtension, ex);
                }
                editorExtension = editorExtension.Next as TextEditorExtension;
            }

            // Parse the file when the document is closed. In this way if the document
            // is closed without saving the changes, the saved compilation unit
            // information will be restored
            if (currentParseFile != null)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                    // Don't access Document properties from the thread
                    ProjectDomService.Parse(curentParseProject, currentParseFile, DesktopService.GetMimeTypeForUri(currentParseFile));
                });
            }
            if (fileDom != null)
            {
                ProjectDomService.RemoveFileDom(FileName);
                fileDom = null;
            }

            Counters.OpenDocuments--;
        }
Esempio n. 7
0
 protected override string GenerateInfo(string filename)
 {
     try {
         var doc = ProjectDomService.Parse(Project, filename) as AspNetParsedDocument;
         if (doc != null && !string.IsNullOrEmpty(doc.Info.InheritedClass))
         {
             return(doc.Info.InheritedClass);
         }
     } catch (Exception ex) {
         LoggingService.LogError("Error reading codebehind name for file '" + filename + "'", ex);
     }
     return(null);
 }
Esempio n. 8
0
//		public IType ImplementInterface (ICompilationUnit pinfo, IType klass, IType iface, bool explicitly, IType declaringClass, IReturnType hintReturnType)
//		{
//			if (klass == null)
//				throw new ArgumentNullException ("klass");
//			if (iface == null)
//				throw new ArgumentNullException ("iface");
//			RefactorerContext gctx = GetGeneratorContext (klass);
//			klass = GetUpdatedClass (gctx, klass);
//
//			bool alreadyImplemented;
//			IReturnType prefix = null;
//
//			List<KeyValuePair<IMember,IReturnType>> toImplement = new List<KeyValuePair<IMember,IReturnType>> ();
//
//			prefix = new DomReturnType (iface);
//
//			// Stub out non-implemented events defined by @iface
//			foreach (IEvent ev in iface.Events) {
//				if (ev.IsSpecialName)
//					continue;
//				bool needsExplicitly = explicitly;
//
//				alreadyImplemented = gctx.ParserContext.GetInheritanceTree (klass).Any (x => x.ClassType != ClassType.Interface && x.Events.Any (y => y.Name == ev.Name));
//
//				if (!alreadyImplemented)
//					toImplement.Add (new KeyValuePair<IMember,IReturnType> (ev, needsExplicitly ? prefix : null));
//			}
//
//			// Stub out non-implemented methods defined by @iface
//			foreach (IMethod method in iface.Methods) {
//				if (method.IsSpecialName)
//					continue;
//				bool needsExplicitly = explicitly;
//				alreadyImplemented = false;
//				foreach (IType t in gctx.ParserContext.GetInheritanceTree (klass)) {
//					if (t.ClassType == ClassType.Interface)
//						continue;
//					foreach (IMethod cmet in t.Methods) {
//						if (cmet.Name == method.Name && Equals (cmet.Parameters, method.Parameters)) {
//							if (!needsExplicitly && !cmet.ReturnType.Equals (method.ReturnType))
//								needsExplicitly = true;
//							else
//								alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix (cmet.ExplicitInterfaces));
//						}
//					}
//				}
//
//				if (!alreadyImplemented)
//					toImplement.Add (new KeyValuePair<IMember,IReturnType> (method, needsExplicitly ? prefix : null));
//			}
//
//			// Stub out non-implemented properties defined by @iface
//			foreach (IProperty prop in iface.Properties) {
//				if (prop.IsSpecialName)
//					continue;
//				bool needsExplicitly = explicitly;
//				alreadyImplemented = false;
//				foreach (IType t in gctx.ParserContext.GetInheritanceTree (klass)) {
//					if (t.ClassType == ClassType.Interface)
//						continue;
//					foreach (IProperty cprop in t.Properties) {
//						if (cprop.Name == prop.Name) {
//							if (!needsExplicitly && !cprop.ReturnType.Equals (prop.ReturnType))
//								needsExplicitly = true;
//							else
//								alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix (cprop.ExplicitInterfaces));
//						}
//					}
//				}
//				if (!alreadyImplemented)
//					toImplement.Add (new KeyValuePair<IMember,IReturnType> (prop, needsExplicitly ? prefix : null));                }
//
//			Ambience ambience = AmbienceService.GetAmbienceForFile (klass.CompilationUnit.FileName);
//			//implement members
//			ImplementMembers (klass, toImplement, ambience.GetString (iface, OutputFlags.ClassBrowserEntries | OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters) +  " implementation");
//			gctx.Save ();
//
//			klass = GetUpdatedClass (gctx, klass);
//			foreach (IType baseClass in iface.SourceProjectDom.GetInheritanceTree (iface)) {
//				if (baseClass.Equals (iface) || baseClass.FullName == "System.Object")
//					continue;
//				klass = ImplementInterface (pinfo, klass, baseClass, explicitly, declaringClass, hintReturnType);
//			}
//
//
//			return klass;
//		}

        IType GetUpdatedClass(RefactorerContext gctx, IType klass)
        {
            IEditableTextFile file   = gctx.GetFile(klass.CompilationUnit.FileName);
            ParsedDocument    doc    = ProjectDomService.Parse(gctx.ParserContext.Project, file.Name, delegate() { return(file.Text); });
            IType             result = gctx.ParserContext.GetType(klass.FullName, klass.TypeParameters.Count, true);

            if (result is CompoundType)
            {
                IType hintType = doc.CompilationUnit.GetType(klass.FullName, klass.TypeParameters.Count);
                if (hintType != null)
                {
                    ((CompoundType)result).SetMainPart(file.Name, hintType.Location);
                }
            }
            return(result);
        }
        protected override void ParseFile(string fileName, IProgressMonitor monitor)
        {
            if (monitor != null)
            {
                monitor.BeginTask(string.Format(GettextCatalog.GetString("Parsing file: {0}"), Path.GetFileName(fileName)), 1);
            }

            try {
                ProjectDomService.Parse(project, fileName, delegate() { return(File.ReadAllText(fileName)); });
                // The call to ProjectDomService.Parse will call UpdateFromParseInfo when done
            } finally {
                if (monitor != null)
                {
                    monitor.EndTask();
                }
            }
        }
        void ParseCallback(object ob, IProgressMonitor monitor)
        {
            string fileName = (string)ob;

            ProjectDomService.Parse(Project, fileName, delegate() { return(File.ReadAllText(fileName)); });

            /*
             * ParseFile (fileName, monitor);
             * lock (rwlock) {
             *      FileEntry file = GetFile (fileName);
             *      if (file != null) {
             *              file.InParseQueue = false;
             *              FileInfo fi = new FileInfo (fileName);
             *              file.LastParseTime = fi.LastWriteTime;
             *      }
             * }*/
        }
Esempio n. 11
0
        public static IMember AddCodeDomMember(IType type, CodeTypeMember newMember)
        {
            bool isOpen;
            var  data           = TextFileProvider.Instance.GetTextEditorData(type.CompilationUnit.FileName, out isOpen);
            var  parsedDocument = ProjectDomService.GetParsedDocument(type.SourceProjectDom, type.CompilationUnit.FileName);

            var insertionPoints = GetInsertionPoints(data, parsedDocument, type);

            var suitableInsertionPoint = GetSuitableInsertionPoint(insertionPoints, type, newMember);

            var dotNetProject = type.SourceProject as DotNetProject;

            if (dotNetProject == null)
            {
                LoggingService.LogError("Only .NET projects are supported.");
                return(null);
            }

            var          generator = dotNetProject.LanguageBinding.GetCodeDomProvider();
            StringWriter sw        = new StringWriter();

            var options = new CodeGeneratorOptions();

            options.IndentString = "\t";
            if (newMember is CodeMemberMethod)
            {
                options.BracingStyle = "C";
            }
            generator.GenerateCodeFromMember(newMember, sw, options);

            suitableInsertionPoint.Insert(data, sw.ToString());
            if (!isOpen)
            {
                try {
                    File.WriteAllText(type.CompilationUnit.FileName, data.Text);
                } catch (Exception e) {
                    LoggingService.LogError(string.Format("Failed to write file '{0}'.", type.CompilationUnit.FileName), e);
                    MessageService.ShowError(GettextCatalog.GetString("Failed to write file '{0}'.", type.CompilationUnit.FileName));
                }
            }
            var newDocument = ProjectDomService.Parse(type.SourceProject as Project, type.CompilationUnit.FileName, data.Text);

            return(newDocument.CompilationUnit.GetMemberAt(suitableInsertionPoint.Location.Line, int.MaxValue));
        }
Esempio n. 12
0
 /// <summary>
 /// This method can take some time to finish. It's not threaded
 /// </summary>
 /// <returns>
 /// A <see cref="ParsedDocument"/> that contains the current dom.
 /// </returns>
 public ParsedDocument UpdateParseDocument()
 {
     parsing = true;
     try {
         string  currentParseFile   = FileName;
         string  mime               = DesktopService.GetMimeTypeForUri(currentParseFile);
         string  currentParseText   = TextEditor.Text;
         Project curentParseProject = Project;
         this.parsedDocument = ProjectDomService.Parse(curentParseProject, currentParseFile, mime, currentParseText);
         if (this.parsedDocument != null && !this.parsedDocument.HasErrors)
         {
             this.lastErrorFreeParsedDocument = parsedDocument;
         }
     } finally {
         parsing = false;
         OnDocumentParsed(EventArgs.Empty);
     }
     return(this.parsedDocument);
 }
        IMember GetMemberToDocument()
        {
            var   parsedDocument = ProjectDomService.Parse(Document.Project, Document.FileName, Document.TextEditorData.Document.MimeType, Document.TextEditorData.Document.Text);
            IType type           = parsedDocument.CompilationUnit.GetTypeAt(textEditorData.Caret.Line, textEditorData.Caret.Column);

            if (type == null)
            {
                return(null);
            }
            IMember result = null;

            foreach (IMember member in type.Members)
            {
                if (member.Location > new DomLocation(textEditorData.Caret.Line + 1, textEditorData.Caret.Column + 1) && (result == null || member.Location < result.Location))
                {
                    result = member;
                }
            }
            return(result);
        }
Esempio n. 14
0
 /// <summary>
 /// This method can take some time to finish. It's not threaded
 /// </summary>
 /// <returns>
 /// A <see cref="ParsedDocument"/> that contains the current dom.
 /// </returns>
 public ParsedDocument UpdateParseDocument()
 {
     try {
         string currentParseFile = FileName;
         var    editor           = Editor;
         if (editor == null)
         {
             return(null);
         }
         string  currentParseText   = editor.Text;
         Project curentParseProject = Project;
         this.parsedDocument = ProjectDomService.Parse(curentParseProject, currentParseFile, currentParseText);
         if (this.parsedDocument != null && !this.parsedDocument.HasErrors)
         {
             this.lastErrorFreeParsedDocument = parsedDocument;
         }
     } finally {
         OnDocumentParsed(EventArgs.Empty);
     }
     return(this.parsedDocument);
 }
Esempio n. 15
0
        /// Synchronizes the bindings between the object and the source code
        public void UpdateBindings(string fileName)
        {
            if (targetObject == null)
            {
                return;
            }

            ParsedDocument doc = ProjectDomService.Parse(project, fileName, null);

            classFile = fileName;

            if (doc != null && doc.CompilationUnit != null)
            {
                IType cls = GetClass();
                UpdateBindings(targetObject, cls);

                if (cls != null)
                {
                    targetObject.GeneratePublic = cls.IsPublic;
                }
            }
        }
Esempio n. 16
0
        void OnDocumentChanged(object o, EventArgs a)
        {
            // Don't directly parse the document because doing it at every key press is
            // very inefficient. Do it after a small delay instead, so several changes can
            // be parsed at the same time.

            if (parsing)
            {
                return;
            }

            parsing = true;
            string currentParseFile = FileName;
            string mime             = DesktopService.GetMimeTypeForUri(currentParseFile);

            GLib.Timeout.Add(ParseDelay, delegate {
                if (closed)
                {
                    return(false);
                }
                parsing = false;
                string currentParseText    = TextEditor.Text;
                Project curentParseProject = Project;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                    // Don't access Document properties from the thread
                    this.parsedDocument = ProjectDomService.Parse(curentParseProject, currentParseFile, mime, currentParseText);
                    if (this.parsedDocument != null && !this.parsedDocument.HasErrors)
                    {
                        this.lastErrorFreeParsedDocument = parsedDocument;
                    }
                    DispatchService.GuiSyncDispatch(delegate {
                        OnDocumentParsed(EventArgs.Empty);
                    });
                });
                return(false);
            });
        }
Esempio n. 17
0
        static void GenerateSteticCodeStructure(DotNetProject project, Stetic.ProjectItemInfo item, Stetic.Component component, Stetic.ComponentNameEventArgs args, bool saveToFile, bool overwrite)
        {
            // Generate a class which contains fields for all bound widgets of the component

            string name     = item != null ? item.Name : component.Name;
            string fileName = GetBuildCodeFileName(project, name);

            if (fileName == null)
            {
                return;
            }

            string ns = "";
            int    i  = name.LastIndexOf('.');

            if (i != -1)
            {
                ns   = name.Substring(0, i);
                name = name.Substring(i + 1);
            }

            if (saveToFile && !overwrite && File.Exists(fileName))
            {
                return;
            }

            if (item != null)
            {
                component = item.Component;
            }

            CodeCompileUnit cu = new CodeCompileUnit();

            if (project.UsePartialTypes)
            {
                CodeNamespace cns = new CodeNamespace(ns);
                cu.Namespaces.Add(cns);

                CodeTypeDeclaration type = new CodeTypeDeclaration(name);
                type.IsPartial      = true;
                type.Attributes     = MemberAttributes.Public;
                type.TypeAttributes = System.Reflection.TypeAttributes.Public;
                cns.Types.Add(type);

                foreach (Stetic.ObjectBindInfo binfo in component.GetObjectBindInfo())
                {
                    // When a component is being renamed, we have to generate the
                    // corresponding field using the old name, since it will be renamed
                    // later using refactory
                    string nname = args != null && args.NewName == binfo.Name ? args.OldName : binfo.Name;
                    type.Members.Add(
                        new CodeMemberField(
                            binfo.TypeName,
                            nname
                            )
                        );
                }
            }
            else
            {
                if (!saveToFile)
                {
                    return;
                }
                CodeNamespace cns = new CodeNamespace();
                cns.Comments.Add(new CodeCommentStatement("Generated code for component " + component.Name));
                cu.Namespaces.Add(cns);
            }

            CodeDomProvider provider = project.LanguageBinding.GetCodeDomProvider();

            if (provider == null)
            {
                throw new UserException("Code generation not supported for language: " + project.LanguageName);
            }

            TextWriter fileStream;

            if (saveToFile)
            {
                fileStream = new StreamWriter(fileName);
            }
            else
            {
                fileStream = new StringWriter();
            }

            try {
                provider.GenerateCodeFromCompileUnit(cu, fileStream, new CodeGeneratorOptions());
            } finally {
                fileStream.Close();
            }

            if (ProjectDomService.HasDom(project))
            {
                // Only update the parser database if the project is actually loaded in the IDE.
                if (saveToFile)
                {
                    ProjectDomService.Parse(project, fileName, "");
                    FileService.NotifyFileChanged(fileName);
                }
                else
                {
                    ProjectDomService.Parse(project, fileName, ((StringWriter)fileStream).ToString());
                }
            }
        }
Esempio n. 18
0
 public static AspNetParsedDocument GetCompileUnit(Project project, string filename, bool ensureUpToDate)
 {
     return(ProjectDomService.Parse(project, filename, null) as AspNetParsedDocument);
 }
Esempio n. 19
0
        void CreateClass(string name, string namspace, string folder)
        {
            string fullName = namspace.Length > 0 ? namspace + "." + name : name;

            CodeRefactorer gen            = new CodeRefactorer(fproject.Project.ParentSolution);
            bool           partialSupport = fproject.Project.UsePartialTypes;

            Stetic.WidgetComponent component = (Stetic.WidgetComponent)rootWidget.Component;

            CodeTypeDeclaration type = new CodeTypeDeclaration();

            type.Name      = name;
            type.IsClass   = true;
            type.IsPartial = partialSupport;
            type.BaseTypes.Add(new CodeTypeReference(component.Type.ClassName));

            // Generate the constructor. It contains the call that builds the widget.

            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            foreach (object val in component.Type.InitializationValues)
            {
                if (val is Enum)
                {
                    ctor.BaseConstructorArgs.Add(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(val.GetType()),
                            val.ToString()
                            )
                        );
                }
                else
                {
                    ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(val));
                }
            }

            if (partialSupport)
            {
                CodeMethodInvokeExpression call = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "Build"
                        )
                    );
                ctor.Statements.Add(call);
            }
            else
            {
                CodeMethodInvokeExpression call = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression("Stetic.Gui"),
                        "Build"
                        ),
                    new CodeThisReferenceExpression(),
                    new CodeTypeOfExpression(fullName)
                    );
                ctor.Statements.Add(call);
            }
            type.Members.Add(ctor);

            // Add signal handlers

            AddSignalsRec(type, component);
            foreach (Stetic.Component ag in component.GetActionGroups())
            {
                AddSignalsRec(type, ag);
            }

            // Create the class
            IType cls = gen.CreateClass(Project.Project, ((DotNetProject)Project.Project).LanguageName, folder, namspace, type);

            if (cls == null)
            {
                throw new UserException("Could not create class " + fullName);
            }

            Project.Project.AddFile(cls.CompilationUnit.FileName, BuildAction.Compile);
            IdeApp.ProjectOperations.Save(Project.Project);

            // Make sure the database is up-to-date
            ProjectDomService.Parse(Project.Project, cls.CompilationUnit.FileName);
        }
Esempio n. 20
0
        static IType CreateClass(Project project, Stetic.ActionGroupComponent group, string name, string namspace, string folder)
        {
            string fullName = namspace.Length > 0 ? namspace + "." + name : name;

            CodeRefactorer gen = new CodeRefactorer(project.ParentSolution);

            CodeTypeDeclaration type = new CodeTypeDeclaration();

            type.Name    = name;
            type.IsClass = true;
            type.BaseTypes.Add(new CodeTypeReference("Gtk.ActionGroup"));

            // Generate the constructor. It contains the call that builds the widget.

            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(fullName));

            CodeMethodInvokeExpression call = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(
                    new CodeTypeReferenceExpression("Stetic.Gui"),
                    "Build"
                    ),
                new CodeThisReferenceExpression(),
                new CodeTypeOfExpression(fullName)
                );

            ctor.Statements.Add(call);
            type.Members.Add(ctor);

            // Add signal handlers

            foreach (Stetic.ActionComponent action in group.GetActions())
            {
                foreach (Stetic.Signal signal in action.GetSignals())
                {
                    CodeMemberMethod met = new CodeMemberMethod();
                    met.Name       = signal.Handler;
                    met.Attributes = MemberAttributes.Family;
                    met.ReturnType = new CodeTypeReference(signal.SignalDescriptor.HandlerReturnTypeName);

                    foreach (Stetic.ParameterDescriptor pinfo in signal.SignalDescriptor.HandlerParameters)
                    {
                        met.Parameters.Add(new CodeParameterDeclarationExpression(pinfo.TypeName, pinfo.Name));
                    }

                    type.Members.Add(met);
                }
            }

            // Create the class

            IType cls = null;

            cls = gen.CreateClass(project, ((DotNetProject)project).LanguageName, folder, namspace, type);
            if (cls == null)
            {
                throw new UserException("Could not create class " + fullName);
            }

            project.AddFile(cls.CompilationUnit.FileName, BuildAction.Compile);
            IdeApp.ProjectOperations.Save(project);

#if TRUNK
            // Make sure the database is up-to-date
            ProjectDomService.Parse(project, cls.CompilationUnit.FileName);
#else
            ProjectDomService.Parse(project, cls.CompilationUnit.FileName, null);
#endif
            return(cls);
        }
Esempio n. 21
0
        public static CompletionDataList CreateProvider(string text, string extension, bool isCtrlSpace)
        {
            string parsedText;
            string editorText;
            int    cursorPosition = text.IndexOf('$');
            int    endPos         = text.IndexOf('$', cursorPosition + 1);

            if (endPos == -1)
            {
                parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1);
            }
            else
            {
                parsedText     = text.Substring(0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring(endPos + 1);
                editorText     = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1);
                cursorPosition = endPos - 1;
            }
            var tww     = new MonoDevelop.CSharpBinding.Tests.TestWorkbenchWindow();
            var sev     = new MonoDevelop.CSharpBinding.Tests.TestViewContent();
            var project = new AspNetAppProject("C#");

            project.FileName = UnitTests.TestBase.GetTempFile(".csproj");

            string file = UnitTests.TestBase.GetTempFile(extension);

            project.AddFile(file);

            ProjectDomService.Load(project);
            ProjectDom dom = ProjectDomService.GetProjectDom(project);

            dom.ForceUpdate(true);
            ProjectDomService.Parse(project, file, delegate { return(parsedText); });
            ProjectDomService.Parse(project, file, delegate { return(parsedText); });

            sev.Project        = project;
            sev.ContentName    = file;
            sev.Text           = editorText;
            sev.CursorPosition = cursorPosition;
            tww.ViewContent    = sev;
            var doc = new MonoDevelop.Ide.Gui.Document(tww);

            doc.ParsedDocument = new MonoDevelop.AspNet.Parser.AspNetParser().Parse(null, sev.ContentName, parsedText);
            foreach (var e in doc.ParsedDocument.Errors)
            {
                Console.WriteLine(e);
            }

            var textEditorCompletion = new MonoDevelop.AspNet.Gui.AspNetEditorExtension();

            Initialize(textEditorCompletion, doc);

            int triggerWordLength     = 1;
            CodeCompletionContext ctx = new CodeCompletionContext();

            ctx.TriggerOffset = sev.CursorPosition;
            int line, column;

            sev.GetLineColumnFromPosition(sev.CursorPosition, out line, out column);
            ctx.TriggerLine       = line;
            ctx.TriggerLineOffset = column - 1;

            if (isCtrlSpace)
            {
                return(textEditorCompletion.CodeCompletionCommand(ctx) as CompletionDataList);
            }
            else
            {
                return(textEditorCompletion.HandleCodeCompletion(ctx, editorText[cursorPosition - 1], ref triggerWordLength) as CompletionDataList);
            }
        }
Esempio n. 22
0
        public IType GetClass(bool getUserClass)
        {
            if (targetObject == null)
            {
                return(null);
            }

            IType cls = gproject.FindClass(className, getUserClass);

            if (cls != null)
            {
                return(cls);
            }

            // The class name may have changed. Try to guess the new name.

            ArrayList        matches = new ArrayList();
            ICompilationUnit unit    = null;
            ProjectDom       ctx     = gproject.GetParserContext();
            ParsedDocument   doc     = ProjectDomService.Parse(project, classFile, null);

            if (doc != null && doc.CompilationUnit != null)
            {
                unit = doc.CompilationUnit;
                foreach (IType fcls in unit.Types)
                {
                    if (IsValidClass(ctx, fcls, targetObject))
                    {
                        matches.Add(fcls);
                    }
                }
            }

            // If found the class, just return it
            if (matches.Count == 1)
            {
                cls               = (IType)matches [0];
                className         = cls.FullName;
                targetObject.Name = className;
                gproject.Save(true);
                return(cls);
            }

            // If not found, warn the user.

            if (unit != null && unit.Types.Count > 0)
            {
                using (SelectRenamedClassDialog dialog = new SelectRenamedClassDialog(unit.Types)) {
                    if (dialog.Run())
                    {
                        className = dialog.SelectedClass;
                        if (className == null)
                        {
                            return(null);
                        }
                        else
                        {
                            targetObject.Name = className;
                            gproject.Save(true);
                            return(gproject.FindClass(className));
                        }
                    }
                }
            }
            else
            {
                MessageService.ShowError(GettextCatalog.GetString("The class bound to the component '{0}' could not be found. This may be due to syntax errors in the source code file.", GetObjectName(targetObject)));
            }

            return(null);
        }
Esempio n. 23
0
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem project, ConfigurationSelector configuration)
        {
            AspNetAppProject aspProject = project as AspNetAppProject;

            //get the config object and validate
            AspNetAppProjectConfiguration config = (AspNetAppProjectConfiguration)aspProject.GetConfiguration(configuration);

            if (config == null)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("Project configuration is invalid. Skipping CodeBehind member generation."));
                return(base.Build(monitor, project, configuration));
            }

            if (config.DisableCodeBehindGeneration)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("Skipping updating of CodeBehind partial classes, because this feature is disabled."));
                return(base.Build(monitor, project, configuration));
            }

            CodeBehindWriter writer = CodeBehindWriter.CreateForProject(monitor, aspProject);

            if (!writer.SupportsPartialTypes)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("The code generator for {0} does not support partial classes. Skipping CodeBehind member generation.",
                                          aspProject.LanguageBinding.Language));;
                return(base.Build(monitor, project, configuration));
            }

            //get the extension used for codebehind files
            string langExt = aspProject.LanguageBinding.GetFileName("a");

            langExt = langExt.Substring(1, langExt.Length - 1);

            List <CodeBehindWarning> errors = new List <CodeBehindWarning> ();

            monitor.Log.WriteLine(GettextCatalog.GetString("Generating CodeBehind members..."));

            bool updatedParseDb = false;

            //go over all the files generating members where necessary
            foreach (ProjectFile file in aspProject.Files)
            {
                WebSubtype type = AspNetAppProject.DetermineWebSubtype(file.FilePath);
                if (type != WebSubtype.WebForm && type != WebSubtype.WebControl && type != WebSubtype.MasterPage)
                {
                    continue;
                }

                //find the designer file
                ProjectFile designerFile = aspProject.Files.GetFile(file.Name + ".designer" + langExt);
                if (designerFile == null)
                {
                    aspProject.Files.GetFile(file.Name + ".Designer" + langExt);
                }
                if (designerFile == null)
                {
                    continue;
                }

                //only regenerate the designer class if it's older than the aspx (etc) file
                if (System.IO.File.GetLastWriteTimeUtc(designerFile.FilePath)
                    > System.IO.File.GetLastWriteTimeUtc(file.FilePath))
                {
                    continue;
                }

                //need parse DB to be up to date
                if (!updatedParseDb)
                {
                    updatedParseDb = true;
                    monitor.Log.Write(GettextCatalog.GetString("Waiting for project type database to finish updating..."));
                    ProjectDom dom = ProjectDomService.GetProjectDom(aspProject);
                    dom.ForceUpdate(true);
                    monitor.Log.WriteLine(GettextCatalog.GetString(" complete."));
                }

                //parse the ASP.NET file
                var parsedDocument = ProjectDomService.Parse(aspProject, file.FilePath) as AspNetParsedDocument;
                if (parsedDocument == null)
                {
                    continue;
                }

                var ccu = CodeBehind.GenerateCodeBehind(aspProject, designerFile.FilePath, parsedDocument, errors);
                if (ccu == null)
                {
                    continue;
                }

                writer.Write(ccu, designerFile.FilePath);
            }

            writer.WriteOpenFiles();

            //write out a friendly message aout what we did
            if (writer.WrittenCount > 0)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("{0} CodeBehind designer classes updated.", writer.WrittenCount));
            }
            else
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("No changes made to CodeBehind classes."));
            }

            //and construct and return a build result
            BuildResult baseResult = base.Build(monitor, project, configuration);

            foreach (CodeBehindWarning cbw in errors)
            {
                if (cbw.FileName != null)
                {
                    baseResult.AddWarning(cbw.FileName, cbw.Line, cbw.Column, null, cbw.WarningText);
                }
                else
                {
                    baseResult.AddWarning(cbw.WarningText);
                }
            }
            return(baseResult);
        }
        public override bool AddToProject(SolutionItem policyParent, Project project, string language, string directory, string name)
        {
            if (!GtkDesignInfo.SupportsDesigner(project))
            {
                ReferenceManager mgr = new ReferenceManager(project as DotNetProject);
                mgr.GtkPackageVersion = mgr.DefaultGtkVersion;
                mgr.Dispose();
            }

            GtkDesignInfo info = GtkDesignInfo.FromProject((DotNetProject)project);

            GuiBuilderProject gproject = info.GuiBuilderProject;

            string fileName = fileTemplate.GetFileName(policyParent, project, language, directory, name);

            fileTemplate.AddToProject(policyParent, project, language, directory, name);

            ProjectDomService.Parse(project, fileName, null);

            DotNetProject netProject = project as DotNetProject;
            string        ns         = netProject != null?netProject.GetDefaultNamespace(fileName) : "";

            string cname    = Path.GetFileNameWithoutExtension(fileName);
            string fullName = ns.Length > 0 ? ns + "." + cname : cname;

            string[,] tags =
            {
                { "Name",      cname    },
                { "Namespace", ns       },
                { "FullName",  fullName }
            };

            XmlElement widgetElem = steticTemplate ["widget"];

            if (widgetElem != null)
            {
                string content = widgetElem.OuterXml;
                content = StringParserService.Parse(content, tags);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);

                gproject.AddNewComponent(doc.DocumentElement);
                gproject.Save(false);
                IdeApp.ProjectOperations.Save(project);
                return(true);
            }

            widgetElem = steticTemplate ["action-group"];
            if (widgetElem != null)
            {
                string content = widgetElem.OuterXml;
                content = StringParserService.Parse(content, tags);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);

                gproject.SteticProject.AddNewActionGroup(doc.DocumentElement);
                gproject.Save(false);
                IdeApp.ProjectOperations.Save(project);
                return(true);
            }

            throw new InvalidOperationException("<widget> or <action-group> element not found in widget template.");
        }
Esempio n. 25
0
        public static System.CodeDom.CodeCompileUnit GenerateCodeBehind(AspNetAppProject project,
                                                                        string filename,
                                                                        AspNetParsedDocument document,
                                                                        List <CodeBehindWarning> errors)
        {
            string className = document.Info.InheritedClass;

            if (document.HasErrors)
            {
                AddFail(errors, document, document.Errors.Where(x => x.ErrorType == ErrorType.Error).First());
                return(null);
            }

            if (string.IsNullOrEmpty(className))
            {
                return(null);
            }

            var refman = new DocumentReferenceManager(project)
            {
                Doc = document
            };
            var memberList = new MemberListVisitor(document, refman);

            document.RootNode.AcceptVisit(memberList);

            var err = memberList.Errors.Where(x => x.ErrorType == ErrorType.Error).FirstOrDefault();

            if (err != null)
            {
                AddFail(errors, document, err);
                return(null);
            }

            //initialise the generated type
            var ccu      = new CodeCompileUnit();
            var namespac = new CodeNamespace();

            ccu.Namespaces.Add(namespac);
            var typeDecl = new System.CodeDom.CodeTypeDeclaration()
            {
                IsClass   = true,
                IsPartial = true,
            };

            namespac.Types.Add(typeDecl);

            //name the class and namespace
            int    namespaceSplit = className.LastIndexOf('.');
            string namespaceName  = null;

            if (namespaceSplit > -1)
            {
                namespac.Name = project.StripImplicitNamespace(className.Substring(0, namespaceSplit));
                typeDecl.Name = className.Substring(namespaceSplit + 1);
            }
            else
            {
                typeDecl.Name = className;
            }

            string masterTypeName = null;

            if (!String.IsNullOrEmpty(document.Info.MasterPageTypeName))
            {
                masterTypeName = document.Info.MasterPageTypeName;
            }
            else if (!String.IsNullOrEmpty(document.Info.MasterPageTypeVPath))
            {
                try {
                    ProjectFile          resolvedMaster       = project.ResolveVirtualPath(document.Info.MasterPageTypeVPath, document.FileName);
                    AspNetParsedDocument masterParsedDocument = null;
                    if (resolvedMaster != null)
                    {
                        masterParsedDocument = ProjectDomService.Parse(project, resolvedMaster.FilePath) as AspNetParsedDocument;
                    }
                    if (masterParsedDocument != null && !String.IsNullOrEmpty(masterParsedDocument.Info.InheritedClass))
                    {
                        masterTypeName = masterParsedDocument.Info.InheritedClass;
                    }
                    else
                    {
                        errors.Add(new CodeBehindWarning(String.Format("Could not find type for master '{0}'",
                                                                       document.Info.MasterPageTypeVPath),
                                                         document.FileName));
                    }
                } catch (Exception ex) {
                    errors.Add(new CodeBehindWarning(String.Format("Could not find type for master '{0}'",
                                                                   document.Info.MasterPageTypeVPath),
                                                     document.FileName));
                    LoggingService.LogWarning("Error resolving master page type", ex);
                }
            }

            if (masterTypeName != null)
            {
                var masterProp = new CodeMemberProperty()
                {
                    Name       = "Master",
                    Type       = new CodeTypeReference(masterTypeName),
                    HasGet     = true,
                    HasSet     = false,
                    Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.New
                                 | System.CodeDom.MemberAttributes.Final,
                };
                masterProp.GetStatements.Add(new System.CodeDom.CodeMethodReturnStatement(
                                                 new System.CodeDom.CodeCastExpression(masterTypeName,
                                                                                       new System.CodeDom.CodePropertyReferenceExpression(
                                                                                           new System.CodeDom.CodeBaseReferenceExpression(), "Master"))));
                typeDecl.Members.Add(masterProp);
            }

            //shortcut building the existing members type map
            if (memberList.Members.Count == 0)
            {
                return(ccu);
            }

            var dom     = refman.TypeCtx.ProjectDom;
            var cls     = dom.GetType(className);
            var members = GetDesignerMembers(memberList.Members.Values, cls, filename, dom, dom);

            //add fields for each control in the page

            foreach (var member in members)
            {
                var type = new CodeTypeReference(member.Type.FullName);
                typeDecl.Members.Add(new CodeMemberField(type, member.Name)
                {
                    Attributes = MemberAttributes.Family
                });
            }
            return(ccu);
        }
Esempio n. 26
0
        internal static RefactoringOptions CreateRefactoringOptions(string text)
        {
            int cursorPosition = -1;
            int endPos         = text.IndexOf('$');

            if (endPos >= 0)
            {
                cursorPosition = endPos;
                text           = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1);
            }

            int selectionStart = -1;
            int selectionEnd   = -1;
            int idx            = text.IndexOf("<-");

            if (idx >= 0)
            {
                selectionStart = idx;
                text           = text.Substring(0, idx) + text.Substring(idx + 2);
                selectionEnd   = idx = text.IndexOf("->");

                text = text.Substring(0, idx) + text.Substring(idx + 2);
                if (cursorPosition < 0)
                {
                    cursorPosition = selectionEnd - 1;
                }
            }

            TestWorkbenchWindow tww = new TestWorkbenchWindow();
            TestViewContent     sev = new TestViewContent();
            //		return new RefactoringOptions ();

            DotNetProject project  = new DotNetAssemblyProject("C#");
            Solution      solution = new Solution();

            solution.RootFolder.Items.Add(project);
            project.FileName = GetTempFile(".csproj");
            string file = GetTempFile(".cs");

            project.AddFile(file);
            string parsedText = text;
            string editorText = text;

            ProjectDomService.Load(project);
            ProjectDom dom = ProjectDomService.GetProjectDom(project);

            dom.ForceUpdate(true);
            ProjectDomService.Parse(project, file, delegate { return(parsedText); });
            ProjectDomService.Parse(project, file, delegate { return(parsedText); });

            sev.Project        = project;
            sev.ContentName    = file;
            sev.Text           = editorText;
            sev.CursorPosition = cursorPosition;

            tww.ViewContent = sev;
            var doc = new MonoDevelop.Ide.Gui.Document(tww);

            doc.Editor.Document.MimeType = "text/x-csharp";
            doc.Editor.Document.FileName = file;
            doc.ParsedDocument           = new McsParser().Parse(null, sev.ContentName, parsedText);
            foreach (var e in doc.ParsedDocument.Errors)
            {
                Console.WriteLine(e);
            }
            if (cursorPosition >= 0)
            {
                doc.Editor.Caret.Offset = cursorPosition;
            }
            if (selectionStart >= 0)
            {
                doc.Editor.SetSelection(selectionStart, selectionEnd);
            }

            NRefactoryResolver resolver = new NRefactoryResolver(dom,
                                                                 doc.ParsedDocument.CompilationUnit,
                                                                 sev.Data,
                                                                 file);

            ExpressionResult expressionResult;

            if (selectionStart >= 0)
            {
                expressionResult = new ExpressionResult(editorText.Substring(selectionStart, selectionEnd - selectionStart).Trim());
                endPos           = selectionEnd;
            }
            else
            {
                expressionResult = new NewCSharpExpressionFinder(dom).FindFullExpression(doc.Editor, cursorPosition + 1);
            }
            ResolveResult resolveResult = endPos >= 0 ? resolver.Resolve(expressionResult, new DomLocation(doc.Editor.Caret.Line, doc.Editor.Caret.Column)) : null;

            RefactoringOptions result = new RefactoringOptions {
                Document      = doc,
                Dom           = dom,
                ResolveResult = resolveResult,
                SelectedItem  = null
            };

            if (resolveResult is MemberResolveResult)
            {
                result.SelectedItem = ((MemberResolveResult)resolveResult).ResolvedMember;
            }
            if (resolveResult is LocalVariableResolveResult)
            {
                result.SelectedItem = ((LocalVariableResolveResult)resolveResult).LocalVariable;
            }
            if (resolveResult is ParameterResolveResult)
            {
                result.SelectedItem = ((ParameterResolveResult)resolveResult).Parameter;
            }
            result.TestFileProvider = new FileProvider(result);
            return(result);
        }
Esempio n. 27
0
 public ParsedDocument ParseDocument()
 {
     return(ProjectDomService.Parse(Dom.Project, Document.FileName, Document.Editor.Text));
 }
Esempio n. 28
0
 public ParsedDocument ParseDocument()
 {
     return(ProjectDomService.Parse(Dom.Project, Document.FileName, DesktopService.GetMimeTypeForUri(Document.FileName), Document.TextEditor.Text));
 }