Source

lyne / lyne / gui / diagramwidget.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import copy
import math

import Tkinter


# Define some constants.
NODE_IS_SINGLETON = 0b001
NODE_HAS_INPUTS   = 0b010
NODE_HAS_OUTPUT   = 0b100

# these are for internal use only.
(_STATE_NO_ITEM_CLICKED,
 _STATE_FIRST_ITEM_CLICKED) = range(0, 2)


def notify(f):
    def wrapper(self, *args, **kwargs):
        f(self, *args, **kwargs)
        self._notify_observers()
    return wrapper


class DiagramWidget(Tkinter.Frame):
    ''' A widget mostly based on a canvas which allows
        for drawing flow-chart like diagrams. The second
        component is a toolbar.

        A diagram consists of "widgets" with directed "lines"
        in between.
    '''
    def __init__(self, master, widget_classes, line_classes): 
        Tkinter.Frame.__init__(self, master)
        self.pack(fill=Tkinter.BOTH, expand=1)

        # possible widget and line classes 
        self.widget_classes = widget_classes
        self.line_classes = line_classes

        self._state = _STATE_NO_ITEM_CLICKED
        self._first_window_id_clicked = None
        self._widgets = {}
        self._lines = {}

        self._temp_new_line = None
        self._observers = []

        self._create_widgets()

    def _create_widgets(self):
        ''' Creates the diagram widget's items.
            To be called once by the constructor.
        '''
        def create_buttons(item_list):
            ''' Helper function that creates the buttons
                in the toolbar above the Canvas widget.
            '''
            for idx, icon in enumerate(item_list):
                if isinstance(icon, Tkinter.PhotoImage):
                    Tkinter.Radiobutton(
                        item_toolbar, 
                        variable=self._toolbar_active_line_index, 
                        image=icon, 
                        value=idx, indicatoron=0).pack(side=Tkinter.LEFT)
                elif isinstance(icon, str):
                    Tkinter.Radiobutton(
                        item_toolbar, 
                        variable=self._toolbar_active_button_index, 
                        text=icon, value=idx, 
                        indicatoron=0).pack(side=Tkinter.LEFT)
                else:
                    raise ValueError, 'An icon must be ' \
                        'Tkinter.PhotoImage ' \
                        'or a string, not %r' % (icon,)

        # Install the toolbar
        # *******************
        self._toolbar_active_button_index = Tkinter.IntVar()
        self._toolbar_active_line_index = Tkinter.IntVar()

        item_toolbar = Tkinter.Frame(self)
        item_toolbar.pack(fill=Tkinter.X)

        # 1. create line buttons
        create_buttons([lc[1] for lc in self.line_classes])

        # 2. create a separator
        Tkinter.Frame(item_toolbar, height=16, width=2, bd=1, 
                      relief=Tkinter.SUNKEN).pack(side=Tkinter.LEFT, padx=5, 
                                                  pady=5, fill=Tkinter.X)

        # 3. create widget buttons through our helper function
        create_buttons([nc[1] for nc in self.widget_classes])


        # Install the canvas; the canvas is embedded in a Frame
        # together with Scrollbar widgets.
        # *****************************************************
        frame = Tkinter.Frame(self, bd=2, relief=Tkinter.SUNKEN)

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # Create scrollbars
        xscrollbar = Tkinter.Scrollbar(frame, orient=Tkinter.HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=Tkinter.E+Tkinter.W)

        yscrollbar = Tkinter.Scrollbar(frame)
        yscrollbar.grid(row=0, column=1, sticky=Tkinter.N+Tkinter.S)

        # Create the canvas widget;
        # Store a reference to the canvas widget so we can
        # access it directly w/o having to go through the
        # frame widget first.
        self._canvas = Tkinter.Canvas(frame, bd=0,
                              xscrollcommand=xscrollbar.set,
                              yscrollcommand=yscrollbar.set,
                              width=800, height=600)

        self._canvas.grid(row=0, column=0,
                          sticky=Tkinter.N+Tkinter.S+Tkinter.E+Tkinter.W)

        xscrollbar.config(command=self._canvas.xview)
        yscrollbar.config(command=self._canvas.yview)

        frame.pack(fill=Tkinter.BOTH, expand=1)

        # Bind mouse events
        # *****************
        Tkinter.Widget.bind(self._canvas, '<Double-Button-1>', 
                            self._handle_mouse_doubleclick)
        Tkinter.Widget.bind(self._canvas, '<Button-1>', 
                            self._handle_mouse_click)
        Tkinter.Widget.bind(self._canvas, '<Motion>', 
                            self._move_temp_new_line)

    def attach_observer(self, observer):
        ''' Attach an observer.
        '''
        if not hasattr(observer, 'notify'):
            raise ValueError, 'The observer object must have a notify() method.'
        self._observers.append(observer)

    def _notify_observers(self):
        ''' Notify our observers that our state has changed.
        '''
        for observer in self._observers:
            observer.notify()

    def _has_widget_type(self, widget_class):
        ''' Do we have this widget type?
        '''
        for widget in self._widgets.values():
            if isinstance(widget, widget_class):
                return True
        return False

    def _move_temp_new_line(self, event):
        ''' Move the new temp. line according to the mouse cursor movements.
        '''
        if self._temp_new_line is None:
            return # short circuit

        old_coords = self._temp_new_line.coords
        new_coords = (old_coords[0],
                      old_coords[1],
                      self._canvas.canvasx(event.x),
                      self._canvas.canvasy(event.y))

        self._temp_new_line.coords = new_coords


    def _handle_mouse_click(self, event):
        ''' Mouse click handler.
        '''
        if self._state == _STATE_FIRST_ITEM_CLICKED:
            # reset main app's state
            self._first_window_id_clicked = None
            self._state = _STATE_NO_ITEM_CLICKED
            self._canvas.delete(self._temp_new_line)
            self._temp_new_line.delete()
            self._temp_new_line = None

    @notify
    def clear_canvas(self):
        ''' This method wipes the canvas as well as the
            underlying data model to start with a clean
            slate.
        '''
        temp_widgets = copy.copy(self._widgets)

        for w_id, widget in temp_widgets.iteritems():
            widget.delete()

        del temp_widgets
        assert self._widgets == {}, ('Expected ' \
            'self._widgets to be {}, not %r' % (
            self._widgets))
        assert self._lines == {}, ('Expected ' \
            'self._lines to be {}, not %r' % (
            self._lines))

    @notify
    def create_widget(self, widget, x, y):
        ''' Creates a widget on our canvas.
        '''
        w_id = self._canvas.create_window((x, y), 
                                          window=widget) 

        # tell the tree item widget what its canvas window id is
        widget.set_window_id(w_id)
        widget.dgw = self

        # save a reference to the tree item widget just created
        # so we can later refer to it by a canvas window id
        self._widgets[w_id] = widget
       
        bbox = self._canvas.bbox(Tkinter.ALL)
        self._canvas.config(scrollregion=(min(bbox[0], 0), min(bbox[1], 0),
                                          bbox[2], bbox[3]))

    def _handle_mouse_doubleclick(self, event):
        ''' Mouse doubleclick handler.
        '''
        if not event.widget.find_withtag(Tkinter.CURRENT):
            # we did not click into a tree widget,
            # so create one
            idx = self._toolbar_active_button_index.get()
            widget_class = self.widget_classes[idx][0]
            if ((self.widget_classes[idx][2] & NODE_IS_SINGLETON) 
                and self._has_widget_type(widget_class)):
               return # short circuit for singleton widgets

            widget = widget_class(self._canvas)
            self.create_widget(widget, event.x, event.y)

    #@notify
    def move_item(self, window_id, delta_x, delta_y):
        ''' Move a tree item widget as well as all lines
            connected to it on the canvas.
        '''

        # do not allow to move an item beyond the upper and/or left border,
        # i.e. coordinates less than 0 are not allowed
        cx, cy = self._canvas.coords(window_id)
        if cx + delta_x < 0:
            delta_x = -cx
        if cy + delta_y < 0:
            delta_y = -cy

        # move the tree item widget
        self._canvas.move(window_id, delta_x, delta_y)

        # update all lines attached to the tree item widget
        widget = self._widgets[window_id]

        for w in widget._lines_out:
            line = self._lines[(widget, w)]
            old_coords = line.coords
            new_coords_line_start = (old_coords[0]+delta_x,
                                     old_coords[1]+delta_y)

            bbox = self._canvas.bbox(w._w_id)
            height = bbox[3] - bbox[1]
            width  = bbox[2] - bbox[0]

            new_coords_line_end = self._get_intersection_w_bbox(
                new_coords_line_start, self._canvas.coords(w._w_id),
                width, height)

            if not new_coords_line_end: return
            
            new_coords = (new_coords_line_start[0],
                          new_coords_line_start[1],
                          new_coords_line_end[0],
                          new_coords_line_end[1])

            line.coords = new_coords

        for w in widget._lines_in:
            line = self._lines[(w, widget)]
        
            old_coords = self._canvas.coords(window_id)
            old_coords2 = line.coords

            bbox = self._canvas.bbox(window_id)
            height = bbox[3] - bbox[1]
            width  = bbox[2] - bbox[0]

            new_coords_line_end = self._get_intersection_w_bbox(
                (old_coords2[0], old_coords2[1]), 
                (old_coords[0]+delta_x, old_coords[1]+delta_y),
                width, height)

            if not new_coords_line_end: return
            
            new_coords = (old_coords2[0],
                          old_coords2[1],
                          new_coords_line_end[0],
                          new_coords_line_end[1])

            line.coords = new_coords

        bbox = self._canvas.bbox(Tkinter.ALL)
        self._canvas.config(scrollregion=(min(bbox[0], 0), min(bbox[1], 0),
                                          bbox[2], bbox[3]))


    def _euklidean_distance(self, (p1_x, p1_y), (p2_x, p2_y)):
        ''' Calculates the euklidean distance between two given points.
        '''
        return math.sqrt((p1_x - p2_x)**2 + (p1_y - p2_y)**2)

    def _get_intersection_w_bbox(self, (p1_x, p1_y), (p2_x, p2_y),
                                 width, height):
        ''' Calculates the intersection of a line between two
            given points and the bounding box of given height and
            width with the second point being the center.
        '''
        dy = float(p2_y - p1_y)
        dx = float(p2_x - p1_x)

        if dy == 0 or dx == 0:
            return None

        m = dy / dx
        z = p1_y - m * p1_x

        g = lambda x: x * m + z

        a = (p2_x - width/2.0, g(p2_x - width/2.0))
        d = (p2_x + width/2.0, g(p2_x + width/2.0))
        if (p2_y - height/2.0) <= d[1] <= (p2_y + height/2.0):
            d_a_p1 = self._euklidean_distance((p1_x, p1_y), a)
            d_d_p1 = self._euklidean_distance((p1_x, p1_y), d)
            if d_a_p1 < d_d_p1:
                return a
            else:
                return d

        b = (((p2_y + height/2.0) - z)/m, p2_y + height/2.0)
        c = (((p2_y - height/2.0) - z)/m, p2_y - height/2.0)
        if (p2_x - width/2.0) <= c[0] <= (p2_x + width/2.0):
            d_b_p1 = self._euklidean_distance((p1_x, p1_y), b)
            d_c_p1 = self._euklidean_distance((p1_x, p1_y), c)
            if d_b_p1 < d_c_p1:
                return b
            else:
                return c
       
        return None
 
    @notify
    def handle_item_plug_click(self, window_id):
        ''' Method for adding lines (=connections) between tree item widgets
            on the canvas and also for updating the underlying data model
            respectively.
        '''
        if self._state == _STATE_NO_ITEM_CLICKED:
            # the user has clicked the first item.
            # create a new line originating in that
            # widget.
            self._first_window_id_clicked = window_id
            self._state = _STATE_FIRST_ITEM_CLICKED
                
            coords_1 = self._canvas.coords(self._first_window_id_clicked)
            coords_2 = self._canvas.coords(window_id)

            # Determine what type of line to create
            # from the selection the user made in the
            # line type button toolbar.
            # TODO We have to store the line type somehow
            # to be able to also store it in a file on
            # disk later.
            line_class = self.line_classes[
                self._toolbar_active_line_index.get()][0]

            # Create new line.
            self._temp_new_line = line_class(self._canvas,
                                        (coords_1[0], coords_1[1], 
                                         coords_2[0], coords_2[1]),
                                        fill='black', width=2)

        elif self._state == _STATE_FIRST_ITEM_CLICKED:
            # the user clicked the second time.
            if window_id == self._first_window_id_clicked:
                # the user clicked into the same widget
                # as he did the first time; delete line.
                self._first_window_id_clicked = None
                self._state = _STATE_NO_ITEM_CLICKED
            else:
                # the user did not click into the first widget
                # a second time, but instead into another
                # widget.

                # check, if the node the user clicked into, has inputs
                # if it does not have input, short circuit
                if not self._widgets[window_id].has_inputs():
                    # short circuit; counting and constant nodes are 
                    # not supposed to get input; they have only outputs.
                    self._first_window_id_clicked = None
                    self._state = _STATE_NO_ITEM_CLICKED
                    return

                line = self._temp_new_line
                coords_1 = self._canvas.coords(self._first_window_id_clicked)
                coords_2 = self._canvas.coords(window_id)
                bbox = self._canvas.bbox(window_id)
                height = bbox[3] - bbox[1]
                width = bbox[2] - bbox[0]
                new_coords = self._get_intersection_w_bbox(coords_1, coords_2,
                                                           width, height)
                if new_coords:
                    coords_2 = new_coords
                line.coords = (coords_1[0], coords_1[1], 
                               coords_2[0], coords_2[1])

                # get references to the involved tree item widgets
                first_widget = self._widgets[
                    self._first_window_id_clicked]
                second_widget = self._widgets[window_id]

                # add line references to the tree item widgets
                first_widget.attach_subwidget(second_widget)
                second_widget.attach_parentwidget(first_widget)
                self._lines[(first_widget, second_widget)] = line

                # update the underlying data model, i.e. attach the
                # 2nd tree as subtree to the 1st tree
                second_widget._tree.attach_subtree(
                    first_widget._tree
                )

                # reset main app's state
                self._first_window_id_clicked = None
                self._state = _STATE_NO_ITEM_CLICKED
                self._temp_new_line = None
        else:
            raise RuntimeError, 'The main app is in an undefined state: %r' % (
                self._state,)