Full text
University of Minho School of Engineering Bruno Pinto Jácome 2D Graph Editor for XML with Semantic Validation october 2023
University of Minho School of Engineering Bruno Pinto Jácome 2D Graph Editor for XML with Semantic Validation Masters Dissertation Master’s in Informatics Engineering Dissertation supervised by António José Borba Ramires Fernandes october 2023
Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: CC BY https://creativecommons.org/licenses/by/4.0/ i
Acknowledgements The first person to whom I extend my heartfelt gratitude is Professor António Ramires. He not only provided me with the opportunity to delve into a subject of great personal interest but also offered unwavering support throughout this journey, constantly motivating me to strive for the best possible results. As this master’s thesis marks the culmination of my academic career, I would like to express my gratitude to all the professors who have played a pivotal role in nurturing my admiration for my chosen field of study. Additionally, I wish to convey my appreciation to my colleagues and friends who have been with me every step of the way. Last but certainly not least, I want to express my gratitude to my family, who have stood by me during these years of hard work. Without their support, I wouldn’t have been able to reach the point where I am today. ii
Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. University of Minho, Braga, october 2023 Bruno Pinto Jácome iii
Abstract Nowadays, XML is one of the most used markup languages for storing and sharing data. As so, special care must be taken when validating the content of these files, ensuring that they comply with the standards defined for the data they represent. In order to ensure that these standards are met, XML validation languages such as DTD, XSD, or Schematron can be used. These languages allow the definition of structural or semantic rules, that need to be followed in order to guarantee that the XML documents contain valid data. In terms of XML visualizing and editing, although there are several XML editors available, many of which have a wide variety of features that make them easier to use, there is a problem that no editor addresses: as these documents grow in size, it becomes more difficult to identify the boundaries of each element, which makes editing these files way harder than it should be. This paper proposes and documents the development of a tool with two main components. The first component is an XML validator that aims to offer greater freedom in defining validation constraints for these files, by allowing users to use a predefined programming language to write functions that will analyze the graph in order to determine if it is both syntactically and semantically correct. The second component, an XML graphic editor, will allow an easier creation, editing, and visualization of these files, by representing them in the form of 2D graphs. Keywords XML, DTD, XSD, Schematron, Graphs iv
Resumo Nos tempos correntes, XML é uma das linguagens de marcação mais utilizadas para armazenamento e partilha de dados. Assim sendo, deve haver um cuidado especial na validação do conteúdo destes ficheiros, garantindo que cumprem os padrões definidos para os dados que representam. De forma a garantir que estes padrões se cumprem, podem ser utilizadas linguagens de validação de XML, como DTD, XSD ou Schematron. Estas linguagens permitem a definição de um conjunto de regras, estruturais ou semânticas, que necessitam ser cumpridas de forma a garantir que os documentos XML apresentam o formato de dados correto. A nivel da visualização e edição de documentos XML, embora existam vários editores de XML disponíveis, muitos dos quais apresentam uma grande variedade de funcionalidades que facilitam a sua utilização, existe um problema que nenhum editor corrige. Consoante estes documentos crescem em dimensões, começa a tornar-se mais dificil identificar os limites de cada elemento, o que torna a edição destes documentos mais complicada do que necessita ser. Neste documento é proposta e documentada a implementação de uma ferramenta que encorpore duas componentes. A primeira é um validador de XML que tem como objetivo dar uma maior liberdade na definição de restrições de validação destes ficheiros, recorrendo à utilização de uma linguagem de programação predefinida para a escrita de funções de que irão correr sob o grafo de forma a determinar se este se encontra sintatica e semanticamente correto. A segunda componente, um editor gráfico de XML, permitirá uma mais fácil criação, edição e visualização destes ficheiros, representando-os sob a forma de grafos 2D. Palavras-chave XML, DTD, XSD, Schematron, Grafos v
Contents I Introductory material 1 1 Introduction 2 1.1 Motivation ...................................... 2 1.2 Objectives ...................................... 3 1.3 Document Structure .................................. 3 2 State of the Art 5 2.1 XML validation .................................... 5 2.1.1 DTD ..................................... 5 2.1.2 XSD ..................................... 7 2.1.3 Schematron ................................. 10 2.2 XML visualization and editing ............................. 12 2.3 Alternative node-based graph tools ........................... 14 2.3.1 Unreal Engine’s Blueprints .......................... 14 2.3.2 Node editor APIs ............................... 15 II Core of the Dissertation 18 3 The problem and its challenges 19 3.1 Direct XML representation ............................... 19 3.2 Semantically based XML representation ........................ 21 3.2.1 Understanding the Graph Template ...................... 22 3.2.2 Understanding node design strategies ..................... 24 3.2.3 Creating node definitions ........................... 25 vi
Acronyms API Application Programming Interface. 15,16,27,31,55,74 CSV Comma-Separated Values. 81 DTD Document Type Definition. 5–13,26,55 FPS Frames Per Second. 71,72,74,75 GUI Graphical User Interface. 15,16 IoC Inversion of Control. 69 JSON JavaScript Object Notation. 12,81 JVM Java Virtual Machine. 55 OOP Object-Oriented Programming. 22,33 REGEX Regular Expressions. 27,30 W3C World Wide Web Consortium. 7 XML Extensible Markup Language. 2,3,5–15,19,21,25,26,32,34–37,39–47,49,51,55,56,59, 61,63,66,67,69–74,79–81,85 XSD XML Schema Definition. 7–13,21,26 xiii
Part I Introductory material 1
Chapter 1 Introduction Extensible Markup Language (XML) is a widely used format for storing and exchanging structured data [Paoli and Sperberg-McQueen,2004]. As this format grows in popularity, more and more tools for working with this type of file start appearing. These tools include editors, whose purpose is to make it easier to modify and navigate the data contained within the XML documents, and validation languages, that can be used to ensure that these documents conform to a particular structure and follow certain rules. In this article, we will study this type of tools in order to determine their strengths and limitations. With that knowledge, we will explore an alternative way of performing those same tasks in a more appropriate manner: by representing the XML documents as node-based graphs. 1.1 Motivation Markup languages play a pivotal role in data storage, and one of the most commonly used ones is XML. To ensure that the data stored in XML documents is accurately represented, it is important to implement strategies for validating the correctness of the document’s structure. XML validation languages are languages that allow users to define the structure and rules that an XML document should follow in order to be considered ”valid”. While most validation languages focus on a structural validation of these file, by restricting which elements and attributes should appear in the document and where they can appear, some other languages deal with validating the documents semantically, ensuring that they follow certain context-related rules. On an unrelated note, although XML files are usually easy to read, as they start growing in size, they become more and more verbose, making it harder to understand their content when looking at it in a regular text editor. In order to make the process of visualizing and modifying XML files simpler, some XML editors were created, implementing a wide variety of features that help the users manage the content of these files. 2
Some of these editors go even further by presenting alternative ways to represent XML data, like using tables and even 2D graphs. 1.2 Objectives The main purpose of this thesis is to explore different ways of representing XML data as node-based graphs, offering an enhanced approach for visualizing, manipulating, and validating the content of these files. The first obstacle that we must face is figuring out how to effectively utilize a node system to represent this file format. This step will require a comprehensive exploration of the different strategies for conveying XML data as nodes, followed by a comparison between all the discovered approaches. To further explore this issue, it may be crucial to take a look at other graph editors that are not related to XML files, as we may be able to adapt such solutions to our specific problem. With this examination, we should be able to understand the strengths and limitations of each strategy, ultimately guiding us toward the optimal solution. With a solution to the graph rendering problem in mind, we must shift our focus into figuring out how to incorporate a validation system into the new representation mode. This system should be as comprehensive as possible, enabling users to establish a variety of constraints that cover most scenarios, which is trivial if we want to create a tool with great appeal to the users. To achieve this, we must study the current XML validation languages, exploring they can be translated to node validation. Finally, after addressing all the previous challenges, the final stage involves testing the developed solution against multiple use cases. This allows us to verify that the tool aligns with the initial objectives, and if it presents a viable approach to handle different scenarios. With this information, we should study any weaknesses that we may find, allowing us to plan a possible solution that could be implemented in the future development of the tool. 1.3 Document Structure The remainder of this thesis is structured as follows: •chapter 2 presents a study on some existing tools for visualizing, editing and validating XML files. •chapter 3 presents the problems and challenges faced during the study and implementation of the product. 3
•chapter 4 presents the study of some use cases for this type of tool. •chapter 5 presents some conclusions about the product’s study and development. 4
Chapter 2 State of the Art To ensure the relevance of this project, an examination of some related tools must be carried out. This includes some of the major XML validation languages, as well as applications for editing and visualizing these files. 2.1 XML validation When consuming data from an XML document, it is of extreme importance to ensure that the data is presented in a specific format and that it follows a defined set of rules, preventing any errors that may occur when processing it. This causes XML validation to become an essential process for all applications or services that use this file type. Some of the most used validation languages are studied and reviewed in the following subsections. 2.1.1 DTD Document Type Definition (DTD) is a widely used XML validation language. It provides users the ability to control the structure of their documents while using a remarkably simple syntax. With this validation language, users can specify the elements, attributes, and text that should exist in the document. Regarding the elements, this language allows specifying the tags that can be used in the document, as the usage of any other tag will lead to a syntax error. Additionally, the hierarchical relationships of the different elements must be defined. This refers to the sequence of child elements/text that should be contained within each element. When it comes to the attributes, the DTD language allows the users to specify all attributes that can be defined inside each element. This includes defining its name, indicating whether they are required or optional, and additionally specifying some restrictions that should apply to its value. Some of the available attribute data types are custom enumerations, unique IDs, or references to other IDs (IDREFs). 5
Example Let’s consider a simple XML file used to represent a sent email, such as the one in Listing 2.1. This file includes a series of important information, such as the subject, the recipients, and the body of the email. 1<?xml version="1.0" encoding="UTF-8"?> 2<email> 3<header> 4<recipient_list> 5<recipient name="John Smith" email="[email protected]"/> 6<recipient name="Sarah Price" email="[email protected]"/> 7</recipient_list> 8<subject>Weekly meeting</subject> 9</header> 10 <body> 11 Please remember that this week's meeting takes place friday at 5pm. 12 </body> 13 </email> Listing 2.1: Example of how an email could be represented in XML When sharing email data using this format, it is crucial to ensure that the files present the expected structure, making it easier to automatically parse them without generating unexpected errors. To achieve that, we can define a simple DTD for this format, such as the one showcased in Listing 2.2. 1<!DOCTYPE email [ 2<!ELEMENT email (header, body)> 3<!ELEMENT header (recipient_list, subject)> 4<!ELEMENT recipient_list (recipient+)> 5<!ELEMENT recipient EMPTY> 6<!ATTLIST recipient name CDATA #REQUIRED> 7<!ATTLIST recipient email CDATA #REQUIRED> 8<!ELEMENT subject (#PCDATA)> 9<!ELEMENT body (#PCDATA)> 10 ]> Listing 2.2: Example of a DTD for email validation Strengths and weaknesses The simplicity of this format makes reading and writing DTD documents very straightforward, thus facilitating their usage for both new and more experienced users. However, this simplicity also means some lack of functionality. 6
One place where we can find this lack of features is in the element’s children capture expressions. In these expressions, there is no operator for defining an unordered group of elements. Because of this, the only way to specify that a group of child elements can appear in any order is to indicate each of the possible orders, separating them by choice operators (”|”). This makes the resulting expressions unnecessarily long, making them more difficult to read and understand [Bex et al.,2004]. Besides that, even though it is possible to indicate that an element can have any child (via the ”ANY” keyword), all children must be valid DTD elements. Therefore, it is not possible to use tags in the document that are not included in the DTD itself. Additionally, although the keyword ”ANY” can be used to define a child element, there is no way to do the same when specifying an attribute. This means that there is no way to indicate that an element can have attributes with unspecified names. Furthermore, even though it is possible to specify an attribute as the ID of the element it belongs to, this ID does not take into account its scope, causing all the IDs to be inserted in a unique ID set. This means that no two attributes of type ID can have the same value, even if they belong to elements with different tags. While this may be the desired behavior in some cases, most of the time these attributes should behave similarly to the primary keys of relational databases, something that is not possible to achieve with the DTD format[Fan,2005]. 2.1.2 XSD XML Schema Definition (XSD) is an XML validation language that was developed and recommended by the World Wide Web Consortium (W3C) [Gao et al.,2009]. This language was developed to replace DTD as a standard for validating the structure of XML documents, given the fact that it fixes most of the limitations present in the previous language. One of the main differences between XSD and DTD is that XSD schemas are written directly in XML, instead of using their own specific format. By doing this, XSD files can be written in any editor that recognizes the XML language and can be validated by any XML parser. This also makes the language easier to understand for users who are already familiar with XML. Example Listing 2.3 shows an example of an XSD schema that allows the validation of emails with the format represented in Listing 2.1. 7
1<?xml version="1.0" encoding="UTF-8"?> 2<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 3 4<xs:element name="email"> 5<xs:complexType> 6<xs:sequence> 7<xs:element name="header" type="headerType"/> 8<xs:element name="body" type="xs:string"/> 9</xs:sequence> 10 </xs:complexType> 11 </xs:element> 12 13 <xs:complexType name="headerType"> 14 <xs:sequence> 15 <xs:element name="recipient_list" type="recipientListType"/> 16 <xs:element name="subject" type="xs:string"/> 17 </xs:sequence> 18 </xs:complexType> 19 20 <xs:complexType name="recipientListType"> 21 <xs:sequence> 22 <xs:element name="recipient" type="recipientType" minOccurs="1" maxOccurs="unbounded"/>,→ 23 </xs:sequence> 24 </xs:complexType> 25 26 <xs:complexType name="recipientType"> 27 <xs:attribute name="name" type="xs:string" use="required"/> 28 <xs:attribute name="email" type="xs:string" use="required"/> 29 </xs:complexType> 30 31 </xs:schema> Listing 2.3: Example of an XSD schema for email validation Strengths and weaknesses Since this validation language presents a greater number of features compared to DTD, it allows a more complete validation than the one possible when using the former language. This increased number of features and the new syntax of the XSD language can lead to larger and more complex schemas. However, with careful organization from the user, these files can ultimately become relatively simple, while still offering much greater expressiveness compared to DTD [Bex et al.,2004]. Alternative languages RELAX NG is a schema language for XML that a set of features that are similar to those of XSD [Clark et al.,2001]. However, this language presents a characteristic that makes it very unique: the existence 8
of two different syntaxes for its schemas. Although the schemas can be written directly in XML, similarly to XSD, this language also offers a simpler and more compact syntax for their schemas, which in some ways can be compared to the DTD syntax. Because of this characteristic, this language is often more appealing to users who prefer cleaner validation files. In Listing 2.4 is presented an example of a Relax NG schema for validating the email format specified in Listing 2.1.Listing 2.5 contains the compact version of that same schema. 1<?xml version="1.0" encoding="UTF-8"?> 2<rng:grammar xmlns:rng="http://relaxng.org/ns/structure/1.0"> 3<rng:start combine="choice"> 4<rng:ref name="email" /> 5</rng:start> 6<rng:define name="email"> 7<rng:element name="email"> 8<rng:element name="header"> 9<rng:element name="recipient_list"> 10 <rng:oneOrMore> 11 <rng:element name="recipient"> 12 <rng:attribute name="name"> 13 <rng:data type="string" /> 14 </rng:attribute> 15 <rng:attribute name="email"> 16 <rng:data type="string" /> 17 </rng:attribute> 18 </rng:element> 19 </rng:oneOrMore> 20 </rng:element> 21 <rng:element name="subject"> 22 <rng:data type="string" /> 23 </rng:element> 24 </rng:element> 25 <rng:element name="body"> 26 <rng:data type="string" /> 27 </rng:element> 28 </rng:element> 29 </rng:define> 30 </rng:grammar> Listing 2.4: Example of a Relax NG schema for email validation Given their similarity in terms of functionalities, there are available tools like Trang, which allow the automatic conversion between DTD, XSD, and Relax NG files [Ltd].1 1Because XSD is the language with the larger number of features, it can only be used as an output in the converter. 9
windows, buttons, input fields, plots, menu bars, and much more. Drawing windows with this tool is generally very straightforward, since it implements an extensive API that allows the creation of a variety of GUI elements in only a handful of lines, as shown in Figure 4 1ImGui::Text("Hello, world %d",123); 2if (ImGui::Button("Save")) { 3MySaveFunction(); 4} 5ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); 6ImGui::SliderFloat("float", &f, 0.0f,1.0f); Figure 4: Example on how to generate a simple window with ImGui Even though ImGui does not provide any features for directly creating node-based graph editors, there are a couple of third-party extensions for this library that implement just that, such as ImGuiNodeEditor [thedmd] and ImNodes [Nelarius]. These tools allow for the creation of programmable graph systems. They provide an API for building the skeleton of a graph canvas, implementing the features that are common to every graph editor application, but allowing the programmers to take control of how the users interact with these features, making it possible to design tools suitable for most use cases. Figure 5 illustrates how to implement a simple node editor using the ImNodes library. Besides the functions for rendering nodes, pins, and links, these libraries also provide a way to manage the user interactions with the graphs, creating a transparent way to control what happens when a user tries to create or delete nodes and links. This makes it very easy to add restrictions and trigger events when the users interact with the graph. 16
1ImNodes::BeginNodeEditor(); 2 3int idx = 1; 4int linkFrom, linkTo; 5 6for (int i=1; i <= 5; i++) 7{ 8ImNodes::BeginNode(idx++); 9 10 ImNodes::BeginNodeTitleBar(); 11 ImGui::Text("Node %d", i); 12 ImNodes::EndNodeTitleBar(); 13 14 if (i == 5) linkTo = idx; 15 ImNodes::BeginInputAttribute(idx++); 16 ImGui::Text("input"); 17 ImNodes::EndInputAttribute(); 18 19 ImGui::SameLine(0,25); 20 21 if (i == 3) linkFrom = idx; 22 ImNodes::BeginOutputAttribute(idx++); 23 ImGui::Text("output"); 24 ImNodes::EndOutputAttribute(); 25 26 ImNodes::EndNode(); 27 } 28 29 // Link from node 3 to node 5 30 ImNodes::Link(idx++, linkFrom, linkTo); 31 32 ImNodes::EndNodeEditor(); Figure 5: Example on how to generate a simple node editor with the ImNodes library 17
Part II Core of the Dissertation 18
Chapter 3 The problem and its challenges As mentioned in chapter 1, editing XML directly in text editors can be a cumbersome task, in particular when dealing with larger and more complex files. To address this issue, we explore an alternative representation mode to this format: by representing the XML document as a node-based graph, we intend to create a simpler way to visualize, edit, and validate these files. In this chapter, our focus revolves around exploring the characteristics of graph based editors, by examining relevant concepts, discussing the challenges that will arise during its implementation, and comparing possible solutions for each problem. To evaluate the effectiveness of the established solutions, we developed a demonstration version of this editor. 3.1 Direct XML representation The most straightforward way to represent XML as a graph is by preserving the structure of the original document. With this representation, each node corresponds to a single XML component, which can be an element, a comment, or plain text content. Inside each node, we can represent all the relevant information, like the tag and attributes for the element nodes, and the text content of comment and text nodes. To preserve the hierarchical structure found in the XML format, the graph must support node linking, creating the connections between a parent and its child nodes. Under this approach, we can take any generic XML document, like the one in Listing 3.1, and directly render it as a graph, as shown in Figure 6. Because this graph representation maintains a direct structural relationship with the original XML document, we can seamlessly incorporate any existing XML validation language into the editor. This enables the same schemas to validate both the text file and the graph representation. 19
1<?xml version="1.0" encoding="UTF-8"?> 2<?graph-template href="./template.xml"?> 3<data> 4<person id="p1"> 5<name>John Doe</name> 6<age>30</age> 7<email>[email protected]</email> 8<reads book="b1"/> 9<drives car="c2"/> 10 </person> 11 <!-- ... Other "person" entries ... --> 12 <book id="b1"> 13 <title>Harry Potter and the Sorcerer's Stone</title> 14 <author>J.K. Rowling</author> 15 <published>1997</published> 16 </book> 17 <!-- ... Other "book" entries ... --> 18 <car id="c1"> 19 <make>Toyota</make> 20 <model>Corolla</model> 21 <year>2022</year> 22 </car> 23 <!-- ... Other "car" entries --> 24 </data> Listing 3.1: Generic data stored on an XML document Figure 6: Partial view of the direct representation of an XML document as a graph 20
While this rendering strategy succeeds in portraying all the information from the original XML document into a graph, it ends up not bringing any significant advantage over using a regular text editor. The idea behind this graphic representation was to create a more compact and organized way of displaying XML data. However, we have noticed a rapid growth in graph size even for relatively small documents, which adds a needless complexity to the appearance and organization of the graphs. It is important to note that while we could significantly reduce the number of nodes in the graph by representing properties such as the Person’s name, age, and email as XML attributes, this would require us to modify the original XML structure, which is not ideal. A different issue that we found involves the connections between nodes. When we display an XML document as a graph, we use the node links to connect each parent element to its children, maintaining the hierarchical structure present in the original document. However, it would be preferable to use these links to display other relationships that may be implicitly portrayed in the data, such as the relationship between the ”person” and ”book” elements that we can find in line 8 of Listing 3.1. 3.2 Semantically based XML representation In order to address the previously mentioned issues, the idea for an alternative graph representation strategy emerged. With this new approach, instead of creating a graph that directly translates the structure of the original document, we can adopt more advanced nodes that focus on the semantic meaning behind the XML data. These new nodes would be defined by the user based on the context of the XML document, allowing the nodes to perfectly represent the data at hand. In the end, this new representation mode should resemble the nodes from Unreal Engine’s Blueprints mentioned in subsection 2.3.1. By looking at Figure 7 we can more easily understand how this type of graph can greatly improve the readability of XML data, compared to Figure 6. When someone wants to employ the XSD or Schematron languages to validate any XML document, they must first create a schema for that language, defining the rules that apply to their specific use case. Similarly, to represent an XML file in this graph editor, a configuration file must also be created, specifying the list of available nodes and the validation rules that apply to each of them. We’ll call this configuration file the ”Graph Template”. Since this editor was created specifically for XML files, we’ll also define this configuration file in the same format. Any XML file can reference its respective graph template by defining a processing instruction like the one present in Listing 3.2. 21
Figure 7: Example of some nodes in the enhanced version of the editor 1<?xml version="1.0" encoding="UTF-8"?> 2<?graph-template href="./template.xml"?> Listing 3.2: Processing instruction used to link the XML file to its respective graph template 3.2.1 Understanding the Graph Template The first aspect that needs to be defined in the template is the list of available nodes. Each node definition contains its name, color, and a list of input and output fields, which we will refer to as node variables. The nodes also incorporate some key concepts from Object-Oriented Programming (OOP), namely abstraction and inheritance. This enables one node to extend another, acquiring all its defined variables. Every variable definition must include some essential information, in order to be properly handled by the graph editor. This includes the variable’s name, data type, default value, and link count. The variable’s data type helps restrict the data that will be inserted in that variable. This property can be selected from an array of common atomic types, such as integers, floats, booleans, and strings. Additionally, the system supports vector data types, which group up to 4 values of a single atomic type in the 22
same variable1. Another data type that is available is enumerations, also known as enums. Enumerations can be defined by the user, offering a fixed set of distinct values to use in the variables. Finally, the last supported data type is called ”node reference”, which allows users to create variables with the type of a node that’s available in the graph template, working similarly to pointers from programming languages like C and C++. Figure 8 illustrates how to define node variables using the different data types and how they look inside the editor. 1<node name="Test_Node"> 2<variables> 3<input name="string_var" dataType="string"/> 4<input name="integer_var" dataType="integer"/> 5<input name="float_var" dataType="float"/> 6<input name="boolean_var" dataType="boolean"/> 7<input name="integer4_var" dataType="integer4"/> 8<input name="float2_var" dataType="float2"/> 9<input name="enum_var" dataType="enum" enumType="Fruit"/> 10 <input name="node_ref_var" dataType="node-ref" nodeType="Person"/>,→ 11 </variables> 12 </node> Figure 8: Example of the available data types for the node variables The variable’s link count property establishes the maximum number of links it can hold simultaneously. This property can be assigned one of three options: ”none”, ”single”, or ”multiple”. By default, input variables are configured with a ”single” link count, while output variables are set to allowing ”multiple” links. Inside the graph editor, each node variable stores a value of the corresponding data type, which can be edited through an input field located within the node itself. Alternatively, users can create connections between input and output variables of different nodes, as long as they share the same data type. Linking two variables is useful to indicate that a value is being propagated between different nodes. When two variables are linked, the input field of the receiving variable will be hidden, since the established connection now defines its value. This behavior is being illustrated in Figure 9. The color and appearance of each variable’s pin will adapt according to its data type and link count. This generates a visual distinction between the different variables, which can help users identify if two 1Vector data types are available for integers, floats, and booleans, but not for strings, enums, and node references. 23
Figure 9: Example on how the field of an input variable disappears when linked to another node variables can be connected. In Listing 3.3 we can see the node definitions that allowed the creation of the graph from Figure 7. 3.2.2 Understanding node design strategies To fully understand the benefits of semantically-based node systems, we must first explore the strategy for converting any data structure into this type of node. Creating nodes to store data is a simple process. It involves examining the data itself, recognizing its inherent structure, and then designing a node that encompasses all the relevant information. In a typical programming language, when defining a class or struct we would represent their internal values as member fields. In the node editor, these data fields would be portrayed as node input variables, resulting in them being displayed in the graph editor inside the respective nodes, providing users with the ability to modify their values. Additionally, if a node contains data that should be accessible by the other nodes, this data should also be represented as output variables, allowing it to be linked to other nodes’ inputs. When working with more complex data, it’s typical to come across nested data structures. To represent this data in the graph, we can create a distinct node type for the different data structures, and then illustrate their relationship by defining a node connection between them. To represent this connection, we must define a ”node reference” variable in each node: the node that represents the outer data structure will define an input variable, with the type of its counterpart node, and an appropriate name that represents the meaning of the relationship; the inner node will define an output variable with its own node type, working similarly to a pointer to that object. Note that while using this strategy to represent data as nodes usually is the simplest solution, every use case is unique, and some cases may benefit from alternative approaches. As so, the graph editor does not enforce any specific strategy, giving users the freedom to choose the approach that best suits their individual needs. 24
1<node name="Entity" isAbstract="true"> 2<variables> 3<input name="id" dataType="string"/> 4<output name="ref" dataType="node-ref" nodeType="[self]" /> 5</variables> 6</node> 7<node name="Book" extends="Entity" color="#32a852"> 8<variables> 9<input name="title" dataType="string"/> 10 <input name="author" dataType="string"/> 11 <input name="published" dataType="integer"/> 12 </variables> 13 </node> 14 <node name="Car" extends="Entity" color="#3269a8"> 15 <variables> 16 <input name="make" dataType="string"/> 17 <input name="model" dataType="string"/> 18 <input name="year" dataType="integer"/> 19 </variables> 20 </node> 21 <node name="Person" extends="Entity" color="#a86d32"> 22 <variables> 23 <input name="name" dataType="string"/> 24 <input name="age" dataType="integer"/> 25 <input name="email" dataType="string"/> 26 <input name="reads" dataType="node-ref" nodeType="Book" linkCount="multiple" /> 27 <input name="drives" dataType="node-ref" nodeType="Car" linkCount="multiple"/> 28 </variables> 29 </node> Listing 3.3: Example of the definition of some nodes in the graph template file 3.2.3 Creating node definitions Now that the fundamentals of this type of node system have been presented, we can apply them to the XML document that we have been using up until now, adapting it to take advantage of the advanced nodes. When defining the nodes of a graph template, the initial stage involves searching for any data structures in the original document that can be represented as nodes. In this example, this leads to the creation of the ”Book”, ”Car”, and ”Person” nodes. Next, we proceeded to identify the data that needs to be stored within each node. For instance, in the case of the ”Book” node, we recognized the necessity to store its ID, title, author, and publication year, which we defined as input variables inside the respective node. After following the same approach to the remaining nodes, we then searched for shared data among them, exploring the possibility of moving certain variables into a base node type. Given that all nodes have an ID field, we created an ”Entity” node, 25
1def remove_unused_nodes(graph): 2for node in graph.getNodes(): 3if node.isInstanceOf("Person"): 4continue 5if len(node.getLinkedNodes("ref")) == 0: 6graph.removeNode(node) Listing 3.6: Example of an automated task for the graph editor written in Python 1<editorTasks pathToScript="./editor_tasks.py"> 2<task title="Remove unused nodes" function="remove_unused_nodes"/> 3<task title="Remove duplicate nodes" function="remove_duplicate_nodes" 4</editorTasks> Listing 3.7: Example of the definition of automated tasks in the template configuration file 3.5 XML to graph conversion With the direct XML graph representation introduced in section 3.1, loading XML files into the graph editor is very straightforward, since the nodes directly translate the original document’s structure. However, after transitioning to the semantically-based node system, this process stopped being so direct, since each node now holds more extensive data that we need to look for in the XML documents. This results in the need to adopt a new conversion strategy, establishing a way to automatically extract all the information about each node from the respective XML file. When we defined the ”Book” node, we specified that it contains an ID, a title, an author, and a publication year. However, we did not specify how these values are represented in the XML document, and as we can see in Listing 3.8, there are multiple ways how they can be represented. To allow the editor to automatically extract the accurate data from the document, we must also specify a series of operations that will be automatically executed in order to create, initialize, and link the different nodes. 3.5.1 Loader execution steps The loader execution section in the graph template specifies the operations that will be performed when loading an XML document. These operations usually consists of specifying which nodes should be created and how they can be linked to each other. Listing 3.9 shows how the loader execution section of the graph template in use could be written. Each operator used in the listing will be explained in subsection 3.5.3. 32
1<book id="b3"> 2<title>1984</title> 3<author>George Orwell</author> 4<published>1949</published> 5</book> 6 7<book> 8<id value="b3"/> 9<title value="1984"/> 10 <author value="George Orwell"/> 11 <published value="1949"/> 12 </book> 13 14 <book id="b3" title="1984" author="George Orwell" published="1949"/> Listing 3.8: Example of different ways to store the book data in the XML document 1<template> 2<!-- ... Node definitions ... --> 3<loaderExecution> 4<loadNodes name="Book" selector="data/book"/> 5<loadNodes name="Car" selector="data/car"/> 6<loadNodes name="Person" selector="data/person"/> 7</loaderExecution> 8</template> Listing 3.9: Example of the loader execution from a graph template 3.5.2 Node loader presets The node loader preset is the sequence of operations that should be executed to initialize a node. As such, it should be defined for each existing node type. Since the node system implement some concepts from OOP, we can also take advantage of these features in the context of node loading. We introduced inheritance to the node system in order to avoid unnecessary variable repetition in similar nodes, by instead declaring them within a single node type which can then be extended as needed. To integrate this concept into the node loading presets, we established that each node preset should only be responsible for initializing the variables it explicitly defines, leaving the initialization of the inherited variables to their respective node preset. This means that, when initializing any node, the editor will also execute the operations that were defined in the preset of its base node type. In Listing 3.10, we showcase the loading presets that were defined for the ”Entity” and ”Book” nodes. Because the ”Book” node extends ”Entity”, loading a new book entry will result in the execution of the operations on line 7 and from lines 17 to 19. Each operator used in the listing will be explained in 33
subsection 3.5.3. 1<node name="Entity" isAbstract="true"> 2<variables> 3<input name="id" dataType="string" linkCount="none" dontHide="true"/> 4<output name="ref" dataType="node-ref" nodeType="[self]"/> 5</variables> 6<loaderPreset> 7<setVariable name="id" value="@id"/> 8</loaderPreset> 9</node> 10 <node name="Book" extends="Entity" color="#32a852"> 11 <variables> 12 <input name="title" dataType="string" linkCount="none"/> 13 <input name="author" dataType="string" linkCount="none"/> 14 <input name="published" dataType="integer" linkCount="none"/> 15 </variables> 16 <loaderPreset> 17 <setVariable name="title" value="title/text()"/> 18 <setVariable name="author" value="author/text()"/> 19 <setVariable name="published" value="published/text()"/> 20 </loaderPreset> 21 </node> 22 <!-- ... Remaining nodes ... --> Listing 3.10: Example of two node loading presets 3.5.3 The defined operations In this section, we will explore the available operations that can be used to fully generate the graphs based on the XML documents. Loading nodes Loading nodes is a crucial operation when parsing the XML document because it allows new nodes to be created from the data within the file. This operation can be specified using the ”loadNodes” XML element. When executed, it will create the specified nodes, and then execute the operations that were defined in the respective node loader preset, fully initializing the new nodes. To correctly load the desired nodes, we need to specify two parameters: the name of the node that’s being created, and the selector expression used to find the sections of the XML document that will originate new nodes. To specify the selector parameter, we can use the XPath language. This powerful and versatile language enables a comprehensive traversal of the document, facilitating the lookup for any desired XML elements. Listing 3.11 demonstrates a few different ways to use this operator. 34
1<!-- Loading a Book node for each "book" element anywhere in the document --> 2<loadNodes name="Book" selector="//book"/> 3 4<!-- Loading a Book node for each "book" element inside the "data" element --> 5<loadNodes name="Book" selector="data/book"/> 6 7<!-- Only loading the Book nodes for elements that contain the attribute "id" --> 8<loadNodes name="Book" selector="data/book[@id]"/> 9 10 <!-- Only loading the Book nodes if the attribute "id" starts with the letter "b" --> 11 <loadNodes name="Book" selector="data/book[starts-with(@id, 'b')]"/> Listing 3.11: Example on how to use the ”loadNodes” loading operator When loading new nodes from within a loader preset, it may be useful to provide a mechanism to directly connect them. To provide some examples of the situations where this feature may prove useful, let’s consider a new type of node for representing a ”Task”. In the XML document, we will assign these tasks to each person by storing them inside those elements, as illustrated in Listing 3.12. 1<person id="p1"> 2<!-- ... name, age, email, etc. ... --> 3<task description="Take out the trash"/> 4<task description="Clean the dishes"/> 5<task description="Feed the dog"/> 6</person> 7<person id="p2"> 8<!-- ... name, age, email, etc. ... --> 9<task description="Buy pasta"/> 10 <task description="Cook dinner"/> 11 <task description="Call Julia"/> 12 </person> Listing 3.12: Modified dataset with tasks for each person When initializing each ”Person” node, it is now necessary to generate the corresponding ”Task” nodes and connect them to the current ”Person” node. To achieve this, we can use the parameter ”parentLink”, specifying how to establish the desired connection between the current and the new nodes. When creating multiple nodes with the same loading operation, this link will be established for all new nodes. However, users can restrict this by specifying the ”parentLinkRestriction” flag, which can be set to ”all”, ”first” or ”last”. In Figure 11, we can see how this feature can be used in order to load and connect the mentioned ”Task” nodes. Besides connecting the new nodes to their parent, users may want to connect the new nodes to each 35
1<!-- Connect all the Tasks nodes to the current "Person" node --> 2<loadNodes name="Task" selector="task" parentLink="new::ref->current::tasks"/> Figure 11: Example on how to use the ”loadNodes” loading operator with parent linking other, creating a sequence of interconnected nodes. To accomplish this, the ”sequenceLink” parameter can be used, establishing a connection between the first node and the second, the second and the third, and so on. Figure 12 showcases an alternative way of connecting the task nodes, using this feature to represent the task order present in the XML document. 1<!-- Connect all the Tasks nodes in sequence and only connect the first to the current "Person" node -->,→ 2<loadNodes name="Task" selector="task" 3sequenceLink="previous::next_task->next::previous_task" 4parentLink="new::ref->current::first_task" parentLinkRestriction="first"/> Figure 12: Example on how to use the ”loadNodes” loading operator with sequence linking Setting variable values Setting node variable values is an essential operation during the node loading phase, as it allows the extraction of relevant data from the document, in order to assign it to the corresponding variables. This 36
operation can be specified by the XML element ”setVariable”, which takes two parameters: the variable name and the expression to find the value in the XML document. For the value expression, the XPath language can be used once again, providing a powerful tool that allows the extraction of the data without any restriction on the XML structure. Because most variable data types only hold a single value, the ”value” parameter can be used to specify the XPath expression that will locate the data to be stored in that variable. In Listing 3.13 we can see how to easily load the variables of the ”Book” node. 1<setVariable name="id" value="@id"/> 2<setVariable name="title" value="title/text()"/> 3<setVariable name="author" value="author/text()"/> 4<setVariable name="published" value="published/text()"/> Listing 3.13: Example on how to use the ”setVariable” loading operator for single value variables However, since some variable data types contain more than one atomic item, such as vectors and multi-value enums, we also present some alternative parameters to address these cases. The ”multi- Value” parameter behaves similarly to the ”value” parameter, but with a crucial difference: it doesn’t stop after finding the first result. Instead, it continues searching for additional data that matches the expression, and then groups all the results into a list, which allows these multi-component variables to be correctly initialized. Alternatively, users can employ any of the ”valueX”, ”valueY”, ”valueZ”, and ”valueW” parameters, modifying only specific components of the variable. To demonstrate how to use these parameters, let’s consider a new node that holds a 3D coordinate in a float3 variable named ”position”. If this value is stored in the XML document as a single attribute, with its various components separated by a character such as a semicolon, we can utilize the ”multiValue” parameter, specifying in the XPath expression that we need to split the data using the appropriate separator. However, if this value is stored using multiple attributes, one for each vector component, we have two ways of parsing it. We can continue using the ”multiValue” parameter, by simply specifying the location of each component in order, separated by the pipe operator (|) in the XPath expression. Alternatively, we can specify each component individually by using the ”valueX”, ”valueY”, ”valueZ”, and ”valueW” parameters. These three distinct approaches for loading this variable are depicted in Figure 13. 37
1<!-- If the value is stored as <pos value="10;20;-30"/> --> 2<setVariable name="position" multiValue="tokenize(pos/@value, ';')"/> 3 4<!-- If the value is stored as <pos x="10" y="20" z="-30"/> --> 5<setVariable name="position" multiValue="pos/@x|pos/@y|pos/@z"/> 6<setVariable name="position" valueX="pos/@x" valueY="pos/@y" valueZ="pos/@z"/> Figure 13: Example on how to use the ”setVariable” loading operator for multi-value variables Creating links between nodes Even though it is possible to directly link nodes when creating them, sometimes this functionality is not enough. If we need to connect two already existing nodes, there must be a strategy for searching and filtering them, allowing users to easily find the exact nodes they are looking for. To achieve this, we’ve implemented the ”createLinks” operator. To use this operator, users must specify the initial and final variables to be used for establishing the connection. When used from inside a node preset, this operator allows creating a link from or to the current node, by using the ”fromCurrent” and ”toCurrent” tags. When using these tags, the only additional parameter that needs to be specified is the name of the variable to use for the connection. Alternatively, the ”from” and ”to” tags can be used, offering a more advanced node-searching mechanism. With these tags, users must specify the name of the desired node and its variable, as the editor will look for any matching result in the graph. These last two options offer an additional parameter called ”filter”. This parameter corresponds to a query that will be executed against each matching node, testing if they verify any specific property, and ignoring the nodes that don’t. When using a filter, users can also specify constant values that can be accessed from within the query. In Listing 3.14 we can see how to use this operator to link the variables ”drives” and ”reads” from the ”Person” node to the respective ”Car” and ”Book” nodes. This operation is being executed inside de ”Person” node loader preset. 38
1<createLinks> 2<from node="Book" variable="ref" filter="node.getVariableValue('id') in book_ids"/> 3<toCurrent variable="reads"/> 4<constant name="book_ids" value="reads/@book" multiple="true"/> 5</createLinks> 6<createLinks> 7<from node="Car" variable="ref" filter="node.getVariableValue('id') in car_ids"/> 8<toCurrent variable="drives"/> 9<constant name="car_ids" value="drives/@car" multiple="true"/> 10 </createLinks> Listing 3.14: Example on how to use the ”createLinks” loading operator Executing external tasks With the already mentioned operators, we try to streamline the process of loading the graphs by offering useful mechanisms for extracting the document’s data and applying it to the nodes. While we tried to define an extensive system that simplifies this process, it is important to recognize that every project is unique, and some may require more advanced data processing. When this is the case, the ”executeTask” operator can be used, allowing users to run a custom script that has read access to the XML document, and write access to the graph, allowing these edge cases to be dealt with using an external programming language. To achieve consistency across the various editor systems, the loading tasks use the same scripting language used for the in-editor tasks and the validation system, ensuring uniformity in all the external scripts. The first parameter passed to this operator is the name of the function that will be executed. All functions used for the tasks need to be implemented in a single external file, which must be specified in the graph template. Because the task functions may need access to the data from the graph and the XML document, they receive a state argument, encompassing all the relevant classes, which allows the users to efficiently extract and manipulate the required information and apply it to the nodes. Optionally, users can pass additional arguments to these functions, by specifying them in the XML operator. Each additional argument must be accompanied by an identifier that specifies the type of the argument, which can be a ”variable” from the current node, a ”literal” value, or even an ”xpath” query result2. Listing 3.15 demonstrates how we could use a task to connect each ”Person” node to the respective ”Book” nodes, providing an alternative to the operator used in Listing 3.14. 2If expecting multiple XPath results, users must add an ”*” to the ending of the argument’s identifier, ensuring that the results will be grouped in a list. 39
1<!-- Operator --> 2<executeTask function="link_person_to_books" arg1="xpath*:reads/@book"/> 1# Python task 2def link_person_to_books(state, book_ids): 3# Get the variables for easy access 4current_node = state.getCurrentNode() 5graph = state.getGraph() 6# Find the matching Book nodes 7for node in graph.getNodes("Book"): 8if node.getVariableValue("id")in book_ids: 9# Create the link 10 from_var = node.getOutputVariable("ref") 11 to_var = current_node.getInputVariable("reads") 12 graph.createLink(from_var, to_var) Listing 3.15: Example on how to use the ”executeTask” loading operator, accompanied by the task’s Python code Loading additional files When storing data in XML documents, there are situations where keeping everything in a single file becomes impractical. Instead, some data may be stored separately in a new file, having its path written in the main document. Any additional XML files can be loaded using the ”loadFiles” operator. This operator uses an XPath selector to identify the path of additional files that must be loaded onto the graph. Whenever a relative path is specified, it will be resolved according to the current file, ensuring that this operator can be called recursively. Listing 3.16 showcases how to use the ”loadFiles” operator to load additional files using both dynamic and static file paths. 1<!-- Dynamically loading files from paths stored as <file path="./my/file.xml"/> --> 2<loadFiles selector="file/@path"/> 3 4<!-- Loading static files by specifying the path as a string literal --> 5<loadFiles selector="'../global/file/path.xml'"/> Listing 3.16: Example on how to use the ”loadFiles” loading operator 40
3.5.4 Error handling One important aspect of the loading process is error handling. When converting an XML file to a graph, it is possible that the file in question does not comply with the structure expected by the graph template, which can cause unexpected behaviors. To prevent this, the conversion process needs to implement some error-handling mechanisms. One way to ensure that the XML files comply with the desired structure is to use XML validation languages. By allowing users to associate a validation schema to their graph template, we can use that schema to validate the documents before converting them into graphs, stopping the process if the schemas generate any errors. Alternatively, we can implement error handlers directly into the loading operators, allowing some error checking to be performed while converting the XML data into a graph. There are two main types of errors that may occur and therefore need to be properly handled. The first type of error occurs when we try to find something in the document that doesn’t exist, like a specific element or attribute. The second type of error occurs when the data loaded from the document does not match the expected type, like an attribute’s value that should be an integer but contains alphabetic characters. To catch these errors, we created two error handlers called ”ifNotFound”, and ”ifInvalid”. These handlers can be set to either ”ignore”, which cancels the operation that generated the error but keeps parsing the remainder of the file, or to ”throw”, which stops the whole parsing process and displays an appropriate error message to inform the user of what went wrong. These error handlers can be set globally to all loading operations, but can also be overridden for specific operations, in case they need to be handled differently. Additionally, when executing a task in Python, it’s the user’s job to detect and handle any error found in the document. These errors can be purposely ignored by the user or raised as exceptions. If they are raised as an exception, they will stop the parsing of the document and will be properly displayed to the user, allowing him to more easily fix issues with their documents. 3.6 Graph to XML conversion In the previous section, we defined a series of operators that allow the users to automate the process of creating their graphs based on existing XML files. Now, all that remains is to determine how to automate the reverse process, allowing the users to automatically convert their graphs back into XML files. Ideally, the information that was defined for converting from XML to graph form would be enough to 41
1<!-- Operator 1: --> 2<createFile path="literal:index.xml"> 3<xmlElement name="data"> 4<xmlText value="variable:index_data"/> 5</xmlElement> 6</createFile> 7 8<!-- Operator 2: --> 9<createFile path="variable:filepath"> 10 <xmlElement name="collection"> 11 <saveNodes linkedTo="entries"/> 12 </xmlElement> 13 </createFile> 1<!-- Output: index.xml --> 2<data> 3Some data here ... 4</data> 5 6<!-- Output: collection.xml --> 7<collection> 8<entry name="username" value="john_smith_87"/> 9<entry name="password" value="secret123"/> 10 <entry name="last_login" value="2023-10-08-15h-39m"/> 11 </collection> Figure 15: Example on how to use the ”createFile” saving operator and the respective output 48
challenge of determining the appropriate position for each node, since the original XML document doesn’t contain any information about node placement. There are multiple algorithms that can calculate the optimal placement for the nodes in a graph, each with its own strengths and weaknesses. Force-directed graph drawing [Fruchterman and Reingold,1991] is a family of algorithms that use attractive and repulsive force vectors in order to position the nodes of a graph in an aesthetically pleasing way. These algorithms tend to focus on the edges of the graph, trying to achieve similar lengths and minimizing overlaps. The problem with these algorithms is that they were designed for undirected graphs, which does not align with our use case. When applying one of these algorithms to this type of graph, it would ignore the typical ”left to right” order of the node connections, positioning them in a more arbitrary manner and potentially leading to a disorganized and confusing layout that fails to capture the inherent organization of this type of graph. Hierarchical graph drawing [North and Woodhull,2002] is a family of algorithms that position the nodes of any oriented graph based on a hierarchy. These algorithms distribute the nodes into either horizontal or vertical layers, such that the edges point in a uniform direction. After assigning each node to a specific layer, the algorithm reorders the nodes inside each layer in order to minimize the number of overlapping edges. When dealing with cyclic graphs, achieving a layout where no edge points backward in the hierarchy is indeed impossible. However, these algorithms frequently employ a range of heuristics that try to minimize such issues, leading to an improved overall arrangement of the nodes. In the end, we’ve integrated an implementation of a hierarchical layout algorithm to the graph editor, allowing the graphs to be automatically organized as needed. 3.7.2 Collapsable nodes When a node is rendered, the editor ensures that all its variables are displayed inside the node’s body, which is required in order to make them accessible to the users. The problem with this approach is that when dealing with larger graphs the editor will always render all their variables, which can consume a significant amount of screen space, potentially leading to an overcrowded and less manageable visual representation. This gets even worse when some node contains an extensive array of variables. To address this issue we’ve added the option to collapse any node, hiding all their variables and therefore simplifying the graph. Upon collapsing a node, the only variables that remain visible are those linked to other nodes and those designated in the graph template with the ”dontHide” flag. This flag can be used to ensure a consistent display of specific data, such as IDs. 49
By collapsing all the nodes in the graph, we can generate a layout that’s significantly more compact vertically, as illustrated in Figure 16. Figure 16: Graph layout before and after collapsing the nodes. 3.7.3 Buit-in nodes During the testing phase for the graph editor, we realized that we were frequently defining certain common nodes across multiple projects. As a consequence, we found ourselves duplicating the node definitions by copying and pasting them from one graph template file into another. To simplify this process for future projects, we’ve integrated a few predefined sets of commonly used nodes into the editor. These nodes can be easily included in a project by specifying that in the graph template, as illustrated in Listing 3.22. 1<template> 2<!-- These attributes are optional, so omitting one is equivalent to assigning it the value "false" -->,→ 3<nodes includeArithmeticUtil="true" includeComparisonUtil="false" includeLogicUtil="false" includeVectorUtil="true">,→ 4<!-- ... Node definitions ... -> 5</nodes> 6</template> Listing 3.22: Example on how to include the built-in nodes in a graph template Moving forward, our intention is to continuously expand the roster of predefined nodes, incorporating any other set of nodes that could prove valuable across multiple projects. 50
Math operators To better understand the types of nodes that we believed would be useful to integrate into the editor, we’ll consider the following scenario: we have an XML file that contains a list of constants, each associated with a name and a value, as shown in Listing 3.23. 1<project> 2<constant name="x" value="10"/> 3<constant name="y" value="x - 6"/> 4</project> Listing 3.23: Example of an XML file containing math expressions When rendering this data in the node editor, there are three different ways to represent the value of the constant ”y”: we can calculate the final value and store it in the node, we can directly store the math equation as a string, or we can create nodes to represent all the mathematical operations that lead to the final value, as illustrated in Figure 17. Figure 17: Three different ways to represent math expressions as nodes Besides integrating these arithmetic operation nodes into the editor, we took the opportunity to go even further and also implement nodes for numeric comparison and boolean operations, as displayed in Figure 18. 51
Figure 18: The arithmetic, numerical comparison and logic operation nodes that were integrated into the editor Vector components The second recurring scenario in various projects involved accessing individual components of vector variables. Because of the way vector variables were implemented in the graph editor, it is not possible to establish connections with their individual components. However, as some projects may require such connections, a new group of nodes was created and integrated into the editor. These new nodes enable users to simulate the construction of a vector value based on its individual components, as illustrated in Figure 19. In addition to enabling the construction of vectors, there may also exist the need to perform the reverse 52
Figure 19: Example on how to connect a float variable to a single vector component process, where a specific component is extracted from an existing vector and linked to another variable. To address this need, a new series of nodes was created, allowing users to carry out such operations, as depicted in Figure 20. Figure 20: Example on how to extract the components of a vector output variable All these new nodes were implemented for the different vector data types that exist in the editor, namely integer, float, and boolean vectors. Additionally, these nodes were implemented to accommodate the different available vector sizes, as shown in Figure 21. 53
Figure 21: The vector ”build” and ”break” nodes that were integrated into the editor 54
Chapter 4 Analysis of the use cases In order to study the usability of the developed tool, several tests were conducted, analyzing some distinct XML use cases. The tests are aimed to evaluate the functionality, user-friendliness, and overall effectiveness of the editor, but they may also analyze the application’s performance in critical scenarios. Two versions of the graph editor were implemented to thoroughly test all use cases. The first implementation of the editor employs a direct XML representation, as introduced in section 3.1. This implementation was developed in C++ and uses the ImGui and ImNodes libraries for graph rendering. Additionally, it uses the DTD language for validating the data. The second implementation of the editor uses the semantically-based node system introduced in section 3.2. It was developed in Java, using the ImGui and NodeEditor libraries for rendering. Additionally, it uses the Jython scripting language1for the editor’s validation rules, as well as for handling the in-editor and graph conversion tasks. All the tests were conducted on a machine featuring an Intel Core i5-12600KF (3.70 GHz) processor, 16.0 GB DDR5 RAM (4000 MHz), an AMD Radeon RX 6600 XT graphics card, and running Windows 11 64-bit. 4.1 The Nau3D engine Nau3D [António Ramires] is a dynamic real-time rendering engine developed by the IT department of Universidade do Minho. It introduces an abstraction layer that overlays the OpenGL API, allowing users to create simple or complex graphic pipelines without the need to write any code. This is the application that inspired the study of a general-purpose XML graph editor. To use this engine, users must create a project file in XML, where they specify the assets and pipelines 1Jython is an implementation of the Python programming language that operates directly within the Java Virtual Machine (JVM), offering great interoperability with the Java programming language. Because Jython is restricted to version 2.7 of Python, a future update to this implementation of the graph editor should address this drawback, by integrating a different Python interpreter that does not have such limitations. 55
to be used by the engine. This includes viewports, cameras, scenes, as well as a multitude of other components. Besides defining the project files, users can also Material Libraries, which are separate XML documents that contain a series of graphics-related components such as textures, shaders, and materials, which can be referenced by the project files. Even though the engine aims to keep these XML files as simple as possible, achieving this becomes increasingly challenging when dealing with more complex projects, which may lead to more abundant errors. Since these project files are composed in XML, we have the opportunity to assess the userfriendliness of the two implementations of the graph editor tool with this file format. This enables us to compare their efficiency in simplifying the process of creating these files. 4.1.1 Direct XML representation Let’s examine a very simple Nau3D project, which we’ve displayed in Listing 4.1. By opening this file in the first implementation of the graph editor, we can generate a direct graph representation of the document, as illustrated in Figure 22. Figure 22: Partial view of the direct representation a ’Nau3D’ project as a graph While this graph editor provides an adequate representation of the XML data, it does not bring any advantage over using a regular text editor to perform the same task, especially if the text editor incorporates useful XML features like syntax highlighting and integration with validation languages. The main objective behind representing this data as a graph was to facilitate content modification. 56
1<?xml version="1.0" ?> 2<project name="Simple Project" > 3<assets> 4<scenes> 5<scene name="Al" param="UNITIZE,SWAP_YZ"> 6<file name="teapot.3ds"/> 7</scene> 8</scenes> 9<viewports> 10 <viewport name="MainViewport"> 11 <CLEAR_COLOR r="1.0" g="1.0" b="1.0" /> 12 </viewport> 13 </viewports> 14 <cameras> 15 <camera name="MainCamera" > 16 <viewport name="MainViewport" /> 17 <TYPE value="PERSPECTIVE"/> 18 <POSITION x="0" y="0" z="3" /> 19 <VIEW x="0" y="0" z="-1.0" /> 20 <NEAR value="0.01"/> 21 <FAR value="10"/> 22 </camera> 23 </cameras> 24 <lights> 25 <light name="Sun"> 26 <DIRECTION x="-2" y="-1" z="-2" /> 27 </light> 28 </lights> 29 <materialLibs> 30 <materialLib filename="project.mlib" /> 31 </materialLibs> 32 </assets> 33 <pipelines> 34 <pipeline name="lighting" default="true"> 35 <pass class="default" name="pass1"> 36 <scenes> 37 <scene name="Al" /> 38 </scenes> 39 <camera name="MainCamera" /> 40 <lights> 41 <light name="Sun" /> 42 </lights> 43 <materialMaps> 44 <map fromMaterial="*" toMaterial="basicMaterial" toLibrary="Simple Materials"/>,→ 45 </materialMaps> 46 </pass> 47 </pipeline> 48 </pipelines> 49 </project> Listing 4.1: A simple ’Nau3D’ project file 57
1<assets> 2<constants> 3<constant name="Test_Constant" value="10"/> 4</constants> 5<scene name="My Scene"> 6<geometry name="Ball" type="SPHERE" SLICES="Test_Constant" STACKS="15" />,→ 7<TRANSLATE x="0" y="Test_Constant" z="0"/> 8</scene> 9</assets> Figure 27: Representation of constants used in vector of the ’Nau3D’ project files and the respective graphs The ”Uniform” nodes The last scenario that we will explore is the ”Uniform” nodes. Because Nau3D is a graphics engine, it allows the usage of shaders, which are functions that execute in the graphics card in order to generate the image that will be rendered in each frame. While these functions mainly use the data from the models on the scene in order to calculate the color of each pixel, they may also need to access some external data, which we refer to as uniforms. These uniforms can include matrices to adjust the coordinates of the triangles, light directions to calculate the scene’s illumination, textures to paint the individual models, as well as any other values that the users may need to solve their particular problems. In the Nau3D project files, these uniforms are specified using a series of text arguments, which indicate the name of the uniform and where its value comes from, as illustrated in Listing 4.5. While we could take a similar approach in the node editor, by storing those same arguments inside string variables, there may be a better solution to this problem. Instead, we can take advantage of the connections between the nodes, linking each uniform directly to the node where they take the value from, creating a simpler representation of the data flow. When importing these uniforms into the graph editor, it’s important to take into consideration their 64
1<material name="basicMaterial"> 2<shader name="basicShader"> 3<values> 4<valueof uniform="cam_pos_1" type="CAMERA" context="my_camera" component="POSITION"/>,→ 5<valueof uniform="cam_pos_2" type="CAMERA" context="CURRENT" component="POSITION"/>,→ 6<valueof uniform="frame_count" type="RENDERER" context="CURRENT" component="FRAME_COUNT"/>,→ 7<valueof uniform="custom_param" type="RENDERER" context="CURRENT" component="MY_CUSTOM_PARAM"/>,→ 8</values> 9</shader> 10 </material> Listing 4.5: The definition of some shader uniforms on a ’Nau3D’ project file individual characteristics, as we may need to load them in distinct ways. The first uniform, which we named ”cam_pos_1”, takes its value from the position of the camera named ”my_camera”. As so, to represent this uniform in the graph, we must find that specific camera and link it to the new ”Uniform” node. The second uniform, which also takes its value from a camera, specifies that the camera in question is the one currently in use by the engine, which may vary between different draw calls. This means that, instead of connecting it to a standard camera node, we must instantiate a specific node which we named ”Current_Camera” and use it to link the respective uniform. This new camera node does not contain any of the input variables from the regular cameras, nor its ”ref” output variable, as it can only be used to extract uniform values. The third specified uniform takes its value from what we call the ”Current_Renderer”. This node is very similar to the ”Current_Camera”, as its only purpose is to allow the uniforms to reference its internal values. The fourth and final uniform, while it appears to also take its value from the ”Current_Renderer”, it specifies a component that does not exist. This happens because the Nau3D engine allows users to specify attributes, which are custom values that they can control from within the engine, allowing them to test different parameters in runtime. Because of these attributes, if the users specify a component that does not exist in the renderer, the loading process will look for an ”Attribute” node with a matching name, linking it to the ”Uniform” node. The node representation of the four different uniforms can be seen in Figure 28 65
Figure 28: Node representation of the uniforms from the ’Nau3D’ engine 4.1.3 Conclusions Upon testing the usability of the implemented tools with the Nau3D project files, we arrived at the following conclusions. While the direct representation of the XML document did not bring any advantages over using a regular text editor, the version with the semantically-based node system allowed us to greatly simplify the handling of these files by grouping all its relevant data into more useful and compact nodes. Furthermore, the ability to create custom connections between the different nodes provided a great visual alternative to the referencing present in the plain text version, while also ensuring a level of control that prevents invalid references from being created. As previously mentioned, creating the graph template file for a substantially large project is a laborintensive task, but it is a one-time effort. Once this file is established, it can be distributed to all the users, enabling them to effortlessly modify their projects using the graph editor. While editing Nau3D project files in a text editor might be intuitive for more experienced users, the graph representation can prove to be especially useful for new users, as they will lack substantial knowledge of the tool. 66
4.2 Other popular applications and frameworks In the previous section, we’ve explored some strategies for employing the developed graph editor in order to enhance the workflow of the Nau3D engine. However, since that use case refers to a very specific application that is only used by a relatively small group of people, it would be advantageous to also study some better known applications. By doing so, we can understand how this graph editor can truly impact the more public. 4.2.1 Maven Apache Maven [Bharathan,2015] is a popular build automation and project management tool for Java. Maven is designed to simplify and standardize the build process for projects, as it helps automate tasks such as compiling source code, managing dependencies, packaging artifacts, running tests, and generating documentation. The heart of a Maven project lies in the ”pom.xml” file, which encapsulates project configurations, dependencies, and build instructions. Since this file is defined in XML, Java developers can take advantage of the implemented graph editor to improve the readability of the presented information, making it easier to manage complex projects and their intricate configurations. To better understand how we can adapt the information on these files and represent it as nodes, we’ll consider one specific project that uses Maven: JUnit 4 [JUnit]. JUnit is a simple framework that allows users to define unit tests for Java projects. While version 5 of JUnit has adopted Gradle as its project build tool, version 4 was written using Maven, so we can focus on that particular version. In Figure 29 we can visualize some of the different components of the mentioned configuration file, and how this information can be represented through nodes. 67
1<project> 2<groupId>junit</groupId> 3<artifactId>junit</artifactId> 4<version>4.13.3-SNAPSHOT</version> 5 6<name>JUnit</name> 7<description>JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.</description>,→ 8<url>http://junit.org</url> 9<inceptionYear>2002</inceptionYear> 10 <organization> 11 <name>JUnit</name> 12 <url>http://www.junit.org</url> 13 </organization> 14 <licenses> 15 <license> 16 <name>Eclipse Public License 1.0</name> 17 <url>http://www.eclipse.org/legal/epl-v10.html</url> 18 <distribution>repo</distribution> 19 </license> 20 </licenses> 21 22 <properties> 23 <jdkVersion>1.5</jdkVersion> 24 <hamcrestVersion>1.3</hamcrestVersion> 25 </properties> 26 27 <dependencies> 28 <dependency> 29 <groupId>org.hamcrest</groupId> 30 <artifactId>hamcrest-core</artifactId> 31 <version>${hamcrestVersion}</version> 32 </dependency> 33 </dependencies> 34 </project> Figure 29: Representation of a Maven POM file as a graph 68
4.2.2 Spring Framework Spring [Johnson et al.,2004] is a powerful and popular framework for building enterprise-level Java applications. It offers a modular solution to various software development challenges, promoting best practices and design patterns. One of the central concepts in the Spring framework is the notion of Inversion of Control (IoC), which allows developers to decouple components and manage application dependencies more effectively. It achieves this by providing a container that manages the creation, configuration, and lifecycle of application objects, or ”beans”. While the configuration of these beans can be performed directly inside the Java code, a popular alternative is to implement it inside an external XML document. When resorting to these configuration files, users could take advantage of a graph representation in order to simplify the entire process of managing project dependencies. In order to understand how this information can be represented as a graph, we will simulate a new spring project for a generic corporation and define an email client dependency as an XML file. This email client is defined as a bean, and it specifies four distinct properties: three email addresses, and a map of spell checker services, all of which will be used internally by the client. The spell checkers are also defined as separate beans, with the English spell checker defining a list of blacklisted words that are forbidden in the emails. Figure 30 illustrates how these beans are represented in the XML file and in the graph editor. 69
1<beans> 2<bean id="emailClient" class="com.example.EmailClient"> 3<property name="personalEmailAddress" value="[email protected]"/> 4<property name="securityEmailAddress" value="[email protected]"/> 5<property name="billingEmailAddress" value="[email protected]"/> 6<property name="spellCheckerServices"> 7<map> 8<entry key="en" value-ref="englishSpellChecker" /> 9<entry key="fr" value-ref="frenchSpellChecker" /> 10 <entry key="pt" value-ref="portugueseSpellChecker" /> 11 </map> 12 </property> 13 </bean> 14 15 <bean id="englishSpellChecker" class="com.example.SpellCheckerService"> 16 <property name="blacklistedWords"> 17 <list> 18 <value>damn</value> 19 <value>hell</value> 20 <value>shoot</value> 21 </list> 22 </property> 23 </bean> 24 25 <bean id="frenchSpellChecker" class="com.example.SpellCheckerService"> 26 <!-- Configure the properties for French spell checker if necessary --> 27 </bean> 28 29 <bean id="portugueseSpellChecker" class="com.example.SpellCheckerService"> 30 <!-- Configure the properties for Portuguese spell checker if necessary --> 31 </bean> 32 </beans> Figure 30: Representation of a Spring ”bean” configuration file as a graph 4.3 Large datasets XML files are often used to store datasets, containing numerous instances of one or more data structures. These files are typically large in terms of size, ranging from a few kilobytes to several gigabytes. This 70
highlights a potential use case for the created XML editors. The Courses from Reed College [University of Washington] is a 277 KB public dataset that contains all the courses available at Reed College in Oregon, USA. This dataset includes information about each course, such as its subject, the assigned instructor, and the date and location of the classes, as can be seen in Listing 4.6 1<course> 2<reg_num>10577</reg_num> 3<subj>ANTH</subj> 4<crse>211</crse> 5<sect>F01</sect> 6<title>Introduction to Anthropology</title> 7<units>1.0</units> 8<instructor>Brightman</instructor> 9<days>M-W</days> 10 <time> 11 <start_time>03:10PM</start_time> 12 <end_time>04:30</end_time> 13 </time> 14 <place> 15 <building>ELIOT</building> 16 <room>414</room> 17 </place> 18 </course> Listing 4.6: One of the entries in the ’Courses from Reed College’ dataset In order to identify the best way to represent this dataset as a graph, multiple tests were conducted, exploring and comparing the different strategies. 4.3.1 Direct XML representation The easiest method for rendering this dataset as a graph is to use the first implemented editor, creating a graph that directly translates the structure of the original XML file. When loading the XML document in the graph editor, we can see that it generates over 18 thousand nodes, even more than the file’s 13 thousand lines. The excessive number of nodes not only adds unnecessary complexity to the graph, which makes it impossible for the users to read, but also severely impacts the editor’s performance, resulting in an average of only 1 Frames Per Second (FPS). In Figure 31 we can see how a single course uses about 27 nodes, originating very convoluted graphs. One way of greatly reducing the number of nodes is to modify the original dataset, storing all the infor- 71
Figure 31: Partial view of the direct representation of the ’Courses from Reed College’ dataset as a graph mation about each course as attributes instead of as text inside distinct elements, as done in Listing 4.7. Besides reducing the size of the XML document itself, this approach also reduces the number of nodes in the generated graph to about 7 hundred, since all attributes are stored directly inside its parent node, as seen in Figure 32. By doing this, we not only improve the readability of the graph but also its performance, going up to around 7 FPS. While this is still not an ideal frame rate, it makes the editor somewhat usable. The problem with this approach is that it requires modifying the structure of the dataset, which might not be an option in some cases. Instead, we can check if the second implementation of the editor can achieve better results. 1<course title="Introduction to Anthropology" instructor="Brightman" reg_num="10577" subj="ANTH" crse="211" sect="F01" units="1.0" days="M-W" start_time="03:10PM" end_time="04:30" building="ELIOT" room="414"/> ,→ ,→ ,→ Listing 4.7: Adapted version of an entry in the ’Courses from Reed College’ dataset, using attributes to store the data 72
Figure 32: Partial view of the direct representation of the ’Courses from Reed College’ adapted dataset as a graph 4.3.2 Enhanced XML representation (version 1) In order to improve the graph representation of this dataset, the second implementation of the editor can be used, taking advantage of the semantically-based node system in order to generate a better-suited graph. To achieve this, we must first define the graph template for this data, by defining the nodes that will be available in the editor. After further studying the dataset, we concluded that 3 types of nodes should be created: Course , Subject , and Location . For each node, we’ve created a series of input variables that will store all the relevant data that’s presented in the dataset, as shown in Listing 4.8. Because this dataset has such a simple structure, the process of converting the graph from and to XML is very straightforward, consisting of simple read/write operations, excluding the need to use any Python scripts. When loading the dataset using this graph template, we generate the graph shown in Figure 33. With this representation, we achieve similar results to the direct representation of the adapted dataset found in Figure 32, the main difference being that now we’ve isolated the location and the subject of each course into separate nodes. We’ve also disposed of the root element of the dataset, as it does not hold any useful information for the graph. Even though this graph contains 21 hundred nodes, which is triple the amount found in the previous 73
presented the greatest number of advantages, as it holds the potential to produce more visually appealing graphs that are also simpler to handle. Despite the prerequisite of having to write the configuration file for each new project, which could demand some effort, this iteration ultimately yields better results, making it a preferable option. Moreover, it incorporates control mechanisms that contribute to the prevention and resolution of errors more fluidly, in contrast to the prior version. Consequently, we recommend a deeper examination of this solution, aiming not only to expand it but also to enhance its current features, rendering it more attractive to users. 5.2 Prospect for future work To assess the various proposed solutions for this type of XML representation, a simplified version of the graph editor was implemented. This development followed an iterative process, where we tested various approaches to solve each problem, comparing them and ultimately adopting the most suitable one. The issue with this development strategy is that it didn’t allow us to perform a significant enough modeling phase for the system’s architecture, which could have contributed to establishing a more stable framework, making it better suited for expansion and with less prone to bugs. Thus, if a desire to further explore this tool arises, the first step should be leveraging the current understanding of the tool in order to model an enhanced architecture, aimed at delivering heightened stability and security. One implemented feature that requires some extra work is the node layout algorithm. While the current implementation provides adequate layouts without node overlapping and with a clear hierarchical organization, it is still far from perfect. This implementation still creates layouts with a lot of links intersecting or going behind other nodes, which harms the appearance of the graph. Besides fixing these issues, other improvements could be added to the algorithm, such as smarter node grouping, allowing the algorithm to recognize related nodes and position them together. This would create distinct regions in the graph for different groups of nodes based on their meaning, which would greatly improve the readability of larger datasets. As the purpose of this tool is to replace conventional text editors in the task of modifying XML documents, it must incorporate several prevalent features from such editors, enhancing its appeal and userfriendliness. One essential feature that should be ported to the graph editor is the ability to undo and redo user inputs, making it easier to revert any mistake that may happen when editing the graphs. Additionally, it should include the essential cut, copy, and paste functionalities, enabling users to fluidly rearrange and replicate the nodes within the graph. Moreover, an additional feature with a lot of potential is the find- 80
and-replace functionality, which could be adapted to the node system, empowering users to easily locate specific nodes or variables, and if desired, automatically modify them. To further improve the usability of these features, a keyboard integration should be deployed, allowing them to be performed using keyboard shortcuts. Whilst we aimed to simplify the process of converting between XML and graph form, users might still encounter challenges in accurately defining these operations, resulting in incorrectly converted data. In the current editor implementation, users might struggle to resolve such errors, as they would need to meticulously examine the specified operations to identify issues. One approach to enhance this process would be to integrate a custom debugger into the editor. Equipped with features such as breakpoints, a visible call stack, and access to the graph’s data, this debugger would enable users to follow the conversion operations, thereby simplifying the process of identifying and fixing the errors. Ideally, this debugger should also be able to debug Python code, ensuring comprehensive coverage of all user-defined procedures. Finally, another way to greatly boost the appeal of this type of tool would be to expand it to support other markup languages, such as JSON,Comma-Separated Values (CSV), or even generic text files. This expansion would enable users to fully leverage the graphical interface, regardless of how their data is formatted. By incorporating this type of functionalities, we would develop a comprehensive graph editor that could be released as a complete application, enabling users to effortlessly visualize and modify their XML documents. 81
Bibliography António Ramires. Nau3d github repository. URL https://github.com/Nau3D/nau. Soběslav Benda, Jakub Klímek, and Martin Nečaský. Using schematron as schema language in conceptual modeling for xml. volume 143, 2013. Lucas Bertolini. Hands-On Game Development without Coding: Create 2D and 3D games with Visual Scripting in Unity . Packt Publishing Ltd, 2018. Geert Jan Bex, Frank Neven, and Jan Van Den Bussche. Dtds versus xml schema: A practical study. volume 67, 2004. doi: 10.1145/1017074.1017095. Raghuram Bharathan. Apache Maven Cookbook . Packt Publishing Ltd, 2015. J. Clark, M. Murata, et al. Relax ng specification. OASIS Committee Specification , 3, 2001. EPIC Games. Unreal engine documentation. URL https://docs.unrealengine.com/4.26/ en-US/ProgrammingAndScripting/Blueprints/QuickStart/. Wenfei Fan. Xml constraints: Specification, analysis, and applications. volume 2006, 2005. doi: 10. 1109/DEXA.2005.204. Thomas M.J. Fruchterman and Edward M. Reingold. Graph drawing by force‐directed placement. Software: Practice and Experience , 21, 1991. ISSN 1097024X. doi: 10.1002/spe.4380211102. Shudi Gao, C Michael Sperberg-McQueen, Henry S Thompson, Noah Mendelsohn, David Beech, and Murray Maloney. W3c xml schema definition language (xsd). World Wide Web Consortium , 3, 2009. Roland Hess. Blender foundations: The essential guide to learning blender 2.5 . Taylor & Francis, 2013. Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Thomas Risberg, Alef Arendsen, Darren Davison, Dmitriy Kopylenko, Mark Pollack, et al. The spring framework-reference documentation. interface , 21:27, 2004. 82
JUnit. Junit 4 github repository. URL https://github.com/junit-team/junit4. Thai Open Source Software Center Ltd. Trang. URL https://relaxng.org/jclark/trang.html. Nelarius. Imnodes. URL https://github.com/Nelarius/imnodes. Stephen C. North and Gordon Woodhull. Online hierarchical graph drawing. Lecture Notes in Computer Science (including subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics) , 2265, 2002. ISSN 16113349. doi: 10.1007/3-540-45848-4_19. ocornut. Dear imgui. URL https://github.com/ocornut/imgui. Jean Paoli and CM Sperberg-McQueen. Extensible markup language ( xml ) 1.0. W3C Recommendation , 0, 2004. ISSN 0039-9450. Paschi Research and Development Inc. Qtassistant. URL https://www.paschidev.com/. Brenden Sewell. Blueprints visual scripting for unreal engine . Packt Publishing Ltd, 2015. Syncro Soft SRL. Oxygen xml editor. URL https://www.oxygenxml.com/. thedmd. Imgui node editor. URL https://github.com/thedmd/imgui-node-editor. University of Washington. Uw xml repository. URL http://aiweb.cs.washington.edu/ research/projects/xmltk/xmldata. 83
Part III Appendices 84
Appendix A Python API Documentation In this chapter, we will document the various wrapper classes that can be used from within Python, in order to allow the users access to the content of their graphs. A.1 StateWrapper The state wrapper is a class that is passed as a parameter when executing python tasks. It contains methods for accessing any information that the user may need to correctly load and save the graphs from or two the respective XML file. Method: getGraph() Description Retrieves the current graph Return value The GraphWrapper object Method: getCurrentNode() Description Retrieves the node that’s being loaded or saved Return value The NodeWrapper object Method: getCurrentPath() Description Retrieves the path of the current file (useful when dealing with multiple files) Return value The path of the current file Method: getCurrentXdmContext() Description Retrieves the current position in the XML document Restricted to The graph loader tasks Return value An XdmItem object (from the Saxon java library) Method: executeXpath(expression) Description Executes an XPath expression relative to the current XML document Restricted to The graph loader tasks Parameter 1 The XPath expression Return value The list of objects caught by the expression 85
Method: executeXpath(expression, context) Description Executes an XPath expression relative to the specified context Restricted to The graph loader tasks Parameter 1 The XPath expression Parameter 2 A specific position from the XML document Return value The list of objects caught by the expression Method: getXmlDocument() Description Retrieves the current XML document Restricted to The graph saver tasks Return value A Document object (from the Dom4j java library) Method: getCurrentXmlElement() Description Retrieves the current XML element Restricted to The graph saver tasks Return value A Document object (from the Dom4j java library) A.2 GraphWrapper The graph wrapper is a class that allows the users to access the nodes of the graph. If the user have ”write” privileges, it also allows him to create and destroy nodes and links. Method: getNodes() Description Retrieves the nodes in the graph Return value A list of NodeWrapper objects Method: getNodes(type) Description Retrieves the nodes in the graph with the specified type Parameter 1 The name of the node type Return value A list of NodeWrapper objects Method: createNode(type) Description Creates a new node of the specified type Restricted to The graph loader tasks Parameter 1 The name of the node type Return value The new NodeWrapper object Method: createLink(fromVariable, toVariable) 86
Description Creates a link between two node variables Restricted to The graph loader tasks Parameter 1 The OutputVariableWrapper object where the link starts Parameter 2 The InputVariableWrapper object where the link ends Method: removeNode(node) Description Removes the specified node from the graph Restricted to The graph loader tasks Parameter 1 The NodeWrapper object to remove A.3 NodeWrapper The node wrapper class allows the users to access the variables contained in the node and the links that connect to them. Method: getName() Description Retrieves the name of the node Return value The name of the node Method: isInstanceOf(name) Description Checks if the node is an instance of the specified type Parameter 1 The name of the node type Return value A boolean Method: getVariable(name) Description Retrieves the specified variable from the node Parameter 1 The name of the variable Return value The VariableWrapper object Method: getInputVariable(name) Description Retrieves the specified input variable from the node Parameter 1 The name of the variable Return value The InputVariableWrapper object Method: getOutputVariable(name) Description Retrieves the specified output variable from the node Parameter 1 The name of the variable Return value The OutputVariableWrapper object Method: getVariableValue(name) 87
Description Retrieves the value of the specified variable Parameter 1 The name of the variable Return value Depends on the variable’s data type Method: getLinkedNodes(name) Description Retrieves the nodes linked to the specified variable Parameter 1 The name of the variable Return value A list of NodeWrapper objects Method: getXdmSource() Description Retrieves the XML position that originated the node Restricted to The graph loader tasks Return value An XdmItem object (from the Saxon java library) Method: setCollapsed(value) Description Collapses or expands the node Restricted to The graph loader tasks Parameter 1 A boolean telling if the node should be collapsed A.4 VariableWrapper The variable wrapper class allows access to its establish links established and to the node that owns the variable. Method: getName() Description Retrieves the name of the variable Return value The name of the variable Method: getDataType() Description Retrieves the name of the variable’s data type Return value The name of the variable’s data type Method: isInput() Description Checks if the variable is an input variable Return value A boolean Method: isOutput() Description Checks if the variable is an output variable Return value A boolean 88
Method: isLinked() Description Checks if the variable is linked to another node Return value A boolean Method: getOwner() Description Retrieves the node that owns the variable Return value A NodeWrapper object Method: getSourceNodeName() Description Retrieves the name of the node type that defined the variable (not necessarily the owner node) Return value The name of the node Method: getLinkedVariables() Description Retrieves the list of variables that are linked to the current one Return value A list of variables A.4.1 InputVariableWrapper If a variable is of type ”input”, it also allows access to the value that it holds and that can usually be modified through the editor’s input field. Method: getValue() Description Retrieves the value of the variable (or null if the variable is linked) Return value Depends on the variable’s data type Method: getDefaultValue() Description Retrieves the default value of the variable Return value Depends on the variable’s data type Method: isDefaultValue() Description Checks if the variable’s current value is equal to it’s default value Return value A boolean Method: getValueAsString() Description Retrieves the value of the variable as a string Return value A string 89