a61d7ef9a8223adcb6fafc5e3470848f969d50dc
[Misc/ipe.git] / ipelets / graph / graph.lua
1 ----------------------------------------------------------------------
2 -- graph ipelet
3 ----------------------------------------------------------------------
4 label = "Graph"
5
6 about = [[ Some features making it easier to work with graphs. ]]
7
8 local deactivateGraphMode = false
9 local moveInvisibleObjects = false
10
11 function toggleGraphMode ()
12    if deactivateGraphMode then
13       deactivateGraphMode = false
14    else 
15       deactivateGraphMode = true
16    end
17 end
18
19 function toggleMoveInvisible ()
20    if moveInvisibleObjects then
21       moveInvisibleObjects = false
22    else 
23       moveInvisibleObjects = true
24    end
25 end
26
27 local editing = false
28 local currMarkId = nil
29
30 --------------------------------------------------------------------------------
31 -- add an edit action for marks ------------------------------------------------
32
33 -- saving the old function
34 function _G.MODEL:graph_backup_actinon_edit () end
35 _G.MODEL.graph_backup_action_edit = _G.MODEL.action_edit
36
37 -- adding support for objects of type reference
38 function _G.MODEL:action_edit()
39    if deactivateGraphMode then
40       self:graph_backup_action_edit()
41       return
42    end
43    local p = self:page()
44    local prim = p:primarySelection()
45    if not prim then
46       self:graph_backup_action_edit()
47       return 
48    end
49    local obj = p[prim]
50    if obj:type() == "reference" then
51       action_edit_reference (self, prim, obj)     
52    else
53       self:graph_backup_action_edit()
54    end
55 end
56
57
58 -- starting to edit a mark
59 function action_edit_reference(model, prim, obj)
60    editing = true
61    currMarkId = prim
62    local p = model:page()
63
64    local pos = obj:matrix() * obj:position()
65    -- print(pos)
66
67    -- creating a circle at the position of the mark
68    local ellipse = {type="ellipse"}
69    ellipse[1] = ipe.Matrix({10, 0, 0, 10, pos.x, pos.y})
70    -- print(ellipse[1])
71    local circ = ipe.Path(model.attributes, {ellipse})
72    p:insert(nil, circ, 0, p:layerOf(prim))
73
74    -- edit the circle instead of the mark itself
75    model:action_edit_path(#p, circ)
76
77    -- print("test")
78 end
79
80 --------------------------------------------------------------------------------
81 -- pressing a key while editing the cycle --------------------------------------
82
83 -- saving old function
84 function _G.EDITTOOL:graph_backup_key(code, modifiers, text) end
85 _G.EDITTOOL.graph_backup_key = _G.EDITTOOL.key
86
87 -- overwriting
88 function _G.EDITTOOL:key(code, modifiers, text)
89    self:graph_backup_key(code, modifiers, text)
90    if deactivateGraphMode then return end
91
92    -- react if and only if we are currently editing a mark and key ESC
93    -- or SPACE is pressed
94    if text ~= "\027" and code ~= 0x20 then return end
95    if not editing then return end
96
97    editing = false
98
99    -- finding new and old position
100    local p = self.model:page()
101    local circ = p[#p]
102    local mark = p[currMarkId]
103    local oldPos = mark:matrix() * mark:position()
104    local newPos = circ:shape()[1][1]:translation()
105
106    -- remove the intermediate step of moving the cycle from the undo
107    -- stack and remove the cycle itself
108    local undoSt = self.model.undo
109    p:remove(#p)
110    table.remove(undoSt)
111
112    -- new action for the undo stack moving the mark and all endpoints
113    -- ending at the mark
114    local t = { label = "edit reference",
115                pno = self.model.pno,
116                vno = self.model.vno,
117                selection = self.model:selection(),
118                original = self.model:page():clone(),
119                matrix = matrix,
120                undo = _G.revertOriginal,}
121    t.redo = function (t, doc)
122       p:transform(currMarkId, ipe.Translation(newPos-oldPos))
123       moveEndpoints(oldPos, newPos, p, self.model)
124    end
125    self.model:register(t)
126 end
127
128 -- function moving all endpoints and intermediate points in polylines
129 -- to newPos, if the squared distance to oldPos is at most sqEps
130 local sqEps = 1
131 function moveEndpoints(oldPos, newPos, p, model)
132    -- print(model.vno)
133    for i, obj, sel, layer in p:objects() do
134       if not p:visible(model.vno, layer) and
135          not moveInvisibleObjects then
136          goto continue
137       end
138       if obj:type() == "path" then
139          local shape = obj:shape()
140          for _, subPath in ipairs(shape) do
141             if (subPath["type"] == "curve") then
142                for _,seg in ipairs(subPath) do
143                   if (seg["type"] == "segment") then
144                      for j, point in ipairs(seg) do
145                         -- print(j, point, oldPos)
146                         if (obj:matrix() * point - oldPos):sqLen() < sqEps then
147                            seg[j] = obj:matrix():inverse() * newPos
148                            -- print("test", seg[j])
149                         end 
150                      end
151                   elseif (seg["type"] == "spline") then
152                      if (obj:matrix() * seg[1] - oldPos):sqLen() < sqEps then
153                         seg[1] = obj:matrix():inverse() * newPos
154                      end
155                      if (obj:matrix() * seg[#seg] - oldPos):sqLen() < sqEps then
156                         seg[#seg] = obj:matrix():inverse() * newPos
157                      end
158                   end
159                end
160             end
161             obj:setShape(shape)
162          end
163       end
164       ::continue::
165    end
166 end
167
168
169 --------------------------------------------------------------------------------
170 -- working with groups ---------------------------------------------------------
171
172 local function regroup(elem)
173    local groupElem = {}
174    for i, obj in ipairs(elem) do
175       if obj[1] ~= nil then
176          groupElem[#groupElem + 1] =  regroup(obj)
177       else 
178          groupElem[#groupElem + 1] = obj
179       end
180    end
181    return ipe.Group(groupElem)
182 end
183
184 local function ungroup(group)
185    local elem = group:elements()
186    local plainElem = {}
187    for i, obj in ipairs(elem) do
188       if (obj:type() == "group") then
189          local subElem, subPlainElem = ungroup(obj)
190          elem[i] = subElem;
191          for _, subObj in ipairs(subPlainElem) do
192             table.insert(plainElem, subObj)
193          end
194       else
195          table.insert(plainElem, obj)
196       end
197    end
198    return elem, plainElem
199 end
200
201 --------------------------------------------------------------------------------
202 -- shorten paths ---------------------------------------------------------------
203
204 function shortenObj(obj, lenSource, lenTarget)
205    if obj:type() == "path" then
206       local shape = obj:shape()
207       for _, subPath in ipairs(shape) do
208          local first = subPath[1]
209          local last = subPath[#subPath]
210          
211          local p1 = obj:matrix() * first[1]
212          local p2 = obj:matrix() * first[2]
213          local pDelta = p2 - p1
214          local pNorm = pDelta:normalized()
215          local newP1 =  p1 + pNorm*lenSource
216          
217          local q1 = obj:matrix() * last[#last]
218          local q2 = obj:matrix() * last[#last - 1]
219          local qDelta = q2 - q1
220          local qNorm = qDelta:normalized()
221          local newQ1 = q1 + qNorm*lenTarget
222
223          first[1] = obj:matrix():inverse() * newP1
224          last[#last] = obj:matrix():inverse() * newQ1
225       end
226       obj:setShape(shape)
227    end
228 end
229
230 function getString(model, string)
231    if ipeui.getString ~= nil then
232       return ipeui.getString(model.ui, "Enter length")
233    else 
234       return model:getString("Enter length")
235    end
236 end
237
238 function shorten(model, num)
239    num = num - 2
240    local lenTarget = 0
241    local lenSource = 0
242    -- local str = ipeui.getString(model.ui, "Enter length")
243    -- local str = model:getString("Enter length")
244    local str = getString(model, "Enter length")
245    if not str or str:match("^%s*$)") then return end
246    if num == 1 then -- shorten target
247       lenTarget = tonumber(str)
248    elseif num == 2 then -- shorten source
249       lenSource = tonumber(str)
250    elseif num == 3 then -- shorten both
251       lenTarget = tonumber(str)
252       lenSource = tonumber(str)
253    end
254
255    -- start to edit the edges
256    local t = { label = "shorten edges",
257                pno = model.pno,
258                vno = model.vno,
259                selection = model:selection(),
260                original = model:page():clone(),
261                matrix = matrix,
262                undo = _G.revertOriginal,}
263    t.redo = function (t, doc)
264       local p = doc[t.pno]
265       for _, i in ipairs(t.selection) do
266          p:setSelect(i, 2)
267       end
268       local p = doc[t.pno]
269       for i, obj, sel, layer in p:objects() do
270          if sel and obj:type() == "group" then
271             local elem, plainElem = ungroup(obj)
272             for _,subobj in pairs(plainElem) do
273                shortenObj(subobj, lenSource, lenTarget)
274             end
275             p:replace(i, regroup(elem))
276          elseif sel then
277             shortenObj(obj, lenSource, lenTarget)
278          end        
279       end
280    end
281    model:register(t)
282 end
283
284
285 methods = {
286    { label = "toggle graph mode", run=toggleGraphMode },
287    { label = "toggle move invisible", run=toggleMoveInvisible },
288    { label = "shorten target", run=shorten },
289    { label = "shorten source", run=shorten },
290    { label = "shorten both", run=shorten },
291 }
292
293 ----------------------------------------------------------------------