example ipe file for the pagenumbers ipelet
[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       -- do nothing if the object is invisible and invisible objects
135       -- should not be moved
136       if not p:visible(model.vno, layer) and
137          not moveInvisibleObjects then
138          goto continue
139       end
140       -- do nothing if it is not a path
141       if obj:type() ~= "path" then
142          goto continue
143       end
144       local shape = obj:shape()
145       for _, subPath in ipairs(shape) do
146          if (subPath["type"] == "curve") then
147             for _,seg in ipairs(subPath) do
148                if (seg["type"] == "segment") then
149                   for j, point in ipairs(seg) do
150                      -- print(j, point, oldPos)
151                      if (obj:matrix() * point - oldPos):sqLen() < sqEps then
152                         seg[j] = obj:matrix():inverse() * newPos
153                         -- print("test", seg[j])
154                      end 
155                   end
156                elseif (seg["type"] == "spline") then
157                   if (obj:matrix() * seg[1] - oldPos):sqLen() < sqEps then
158                      seg[1] = obj:matrix():inverse() * newPos
159                   end
160                   if (obj:matrix() * seg[#seg] - oldPos):sqLen() < sqEps then
161                      seg[#seg] = obj:matrix():inverse() * newPos
162                   end
163                end
164             end
165          end
166          obj:setShape(shape)
167       end
168       ::continue::
169    end
170 end
171
172
173 --------------------------------------------------------------------------------
174 -- working with groups ---------------------------------------------------------
175
176 local function regroup(elem)
177    local groupElem = {}
178    for i, obj in ipairs(elem) do
179       if obj[1] ~= nil then
180          groupElem[#groupElem + 1] =  regroup(obj)
181       else 
182          groupElem[#groupElem + 1] = obj
183       end
184    end
185    return ipe.Group(groupElem)
186 end
187
188 local function ungroup(group)
189    local elem = group:elements()
190    local plainElem = {}
191    for i, obj in ipairs(elem) do
192       if (obj:type() == "group") then
193          local subElem, subPlainElem = ungroup(obj)
194          elem[i] = subElem;
195          for _, subObj in ipairs(subPlainElem) do
196             table.insert(plainElem, subObj)
197          end
198       else
199          table.insert(plainElem, obj)
200       end
201    end
202    return elem, plainElem
203 end
204
205 --------------------------------------------------------------------------------
206 -- shorten paths ---------------------------------------------------------------
207
208 function shortenObj(obj, lenSource, lenTarget)
209    if obj:type() == "path" then
210       local shape = obj:shape()
211       for _, subPath in ipairs(shape) do
212          local first = subPath[1]
213          local last = subPath[#subPath]
214          
215          local p1 = obj:matrix() * first[1]
216          local p2 = obj:matrix() * first[2]
217          local pDelta = p2 - p1
218          local pNorm = pDelta:normalized()
219          local newP1 =  p1 + pNorm*lenSource
220          
221          local q1 = obj:matrix() * last[#last]
222          local q2 = obj:matrix() * last[#last - 1]
223          local qDelta = q2 - q1
224          local qNorm = qDelta:normalized()
225          local newQ1 = q1 + qNorm*lenTarget
226
227          first[1] = obj:matrix():inverse() * newP1
228          last[#last] = obj:matrix():inverse() * newQ1
229       end
230       obj:setShape(shape)
231    end
232 end
233
234 function getString(model, string)
235    if ipeui.getString ~= nil then
236       return ipeui.getString(model.ui, "Enter length")
237    else 
238       return model:getString("Enter length")
239    end
240 end
241
242 function shorten(model, num)
243    num = num - 2
244    local lenTarget = 0
245    local lenSource = 0
246    -- local str = ipeui.getString(model.ui, "Enter length")
247    -- local str = model:getString("Enter length")
248    local str = getString(model, "Enter length")
249    if not str or str:match("^%s*$)") then return end
250    if num == 1 then -- shorten target
251       lenTarget = tonumber(str)
252    elseif num == 2 then -- shorten source
253       lenSource = tonumber(str)
254    elseif num == 3 then -- shorten both
255       lenTarget = tonumber(str)
256       lenSource = tonumber(str)
257    end
258
259    -- start to edit the edges
260    local t = { label = "shorten edges",
261                pno = model.pno,
262                vno = model.vno,
263                selection = model:selection(),
264                original = model:page():clone(),
265                matrix = matrix,
266                undo = _G.revertOriginal,}
267    t.redo = function (t, doc)
268       local p = doc[t.pno]
269       for _, i in ipairs(t.selection) do
270          p:setSelect(i, 2)
271       end
272       local p = doc[t.pno]
273       for i, obj, sel, layer in p:objects() do
274          if sel and obj:type() == "group" then
275             local elem, plainElem = ungroup(obj)
276             for _,subobj in pairs(plainElem) do
277                shortenObj(subobj, lenSource, lenTarget)
278             end
279             p:replace(i, regroup(elem))
280          elseif sel then
281             shortenObj(obj, lenSource, lenTarget)
282          end        
283       end
284    end
285    model:register(t)
286 end
287
288
289 methods = {
290    { label = "toggle graph mode", run=toggleGraphMode },
291    { label = "toggle move invisible", run=toggleMoveInvisible },
292    { label = "shorten target", run=shorten },
293    { label = "shorten source", run=shorten },
294    { label = "shorten both", run=shorten },
295 }
296
297 ----------------------------------------------------------------------