File: gvb

package info (click to toggle)
gvb 1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 852 kB
  • ctags: 124
  • sloc: python: 1,256; makefile: 3
file content (481 lines) | stat: -rwxr-xr-x 16,758 bytes parent folder | download
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/python3


# GVB - a GTK+/GNOME vibrations simulator
#
# Copyright © 2008-2013 Pietro Battiston
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from gi.repository import Gtk, GObject, GLib, Gdk
import os

from scipy import array, sin, pi, zeros, shape
from time import time

from gvbmod import dispositions, calculators, points, drawers
from gvbmod.advancededitor import AdvancedEditor


from gvbmod.gvbi18n import _


import locale
import gettext

__version__ = '1.4'

########################## CONFIGURATION #######################################

APP = 'gvb'

import sys

not_installed_dir = os.path.dirname(os.path.realpath(__file__))
if os.path.exists(not_installed_dir + '/stuff/gvb.svg'):
    STUFF_DIR = not_installed_dir + '/stuff'
    HELP_DIR = not_installed_dir + '/help'
    LOCALE_DIR = not_installed_dir + '/locale'
    INSTALLED = False
else:
    for directory in [sys.prefix, sys.prefix + '/local']:
        installed_root_dir = directory + '/share'
        if os.path.exists(installed_root_dir + '/%s/stuff' % APP):
            STUFF_DIR = installed_root_dir + '/%s/stuff' % APP
            LOCALE_DIR = installed_root_dir + '/locale'
            break
    INSTALLED = True


########################## END OF CONFIGURATION ################################


gettext.install(APP, localedir=LOCALE_DIR)
locale.bindtextdomain(APP, LOCALE_DIR)

DIMS = [1,2] #(Still) no fluid dinamics...
WAIT_FRAMES = True        #If computer is too slow and we loose frames, shall we fake them (False) or wait for them at the cost of (willingly) altering speed (True)?
                        #Notice that probably speed gets altered anyway. I imagine that if GObject.timeout_add calls can't get run, they just get queued, not lost.

class MainGbv():
    def __init__(self):
        self.STEPS = 127 #Number of points (per dimension). Suggestion: should be of the form 3^a*4^b*5^c...-1 or simply, 2^n-1.
        self.filename = None
        self.dumping = False
        self.inhibit_dumping = False
        self.occupied = False

        xml=Gtk.Builder()
        
        xml.set_translation_domain('gvb')

        xml.add_from_file(STUFF_DIR + '/gvb.glade')

        self.xml=xml
        self.main=xml.get_object('main')
        self.drawing=xml.get_object('drawing')
        self.start_button=xml.get_object('start button')
        self.frame_number=xml.get_object('frame number')
        self.frame_ms=xml.get_object('frame ms')
        self.draw_ms_label=xml.get_object('draw ms')
        self.calculator_entry=xml.get_object('calculator entry')
        self.ready=True        #This is used to block "draw" and "initialize" dummy calls
        self.inhibit_reconfigure=False
        self.inhibit_change_dim=False

        self.cr=None        #DrawingArea's Drawable is not created until it's not show()n

        self.editor = None

        #Startup situation
        self.shape = (self.STEPS,)
        self.dim = len(self.shape)
        self.disposition='sin'
        self.startpos = None
        self.points = None
        self.MPF = int(1000/self.xml.get_object('mpf').get_value())        #Milliseconds per (drawn) frame (25 ==> 40 frames per second) are then taken from GUI
        self.actual_drawers = [None for dim in DIMS]                #One per dimension

        #Two counters representing drawn frames' ("real") time and calc ("anticipately calculated") time: both in ms.
        self.drawn_time=0
        self.calc_time=0
        self.set_text_counter=0
        self.speed=self.xml.get_object('speed').get_value()

        self.runner=None

        self.dispositions_menu()
        self.calculators_menu()

        xml.connect_signals(self)
        self.initialize()

    def initialize(self, *args):
        self.stop()

        if not self.ready:
            return


        if self.points:
            self.actual_drawers[len(self.points.shape)-1] = self.points.drawer.dr_type

        self.points=points.Points(    shape = self.shape,
                                    gr = self.xml.get_object('granularity').get_value(),
                                    disp = self.disposition,
                                    calc = self.xml.get_object('combo calculator').get_active_text(),
                                    drawer = drawers.Drawer(self.drawing, self.xml.get_object('combo drawer'), dr_type = self.actual_drawers[len(self.shape)-1]),
                                    pos = self.startpos)


        self.xml.get_object('granularity').set_sensitive(self.points.calculator.discrete)



        self.drawn_time=0

        self.frame_number.set_text('1')
        self.frame_ms.set_text('')
        self.draw_ms_label.set_text('')

    def change_speed(self, spin, *args):
        self.speed=float(spin.get_value())

    def change_granularity(self, spin, *args):
        self.points.reconfigure(gr=spin.get_value())

    def change_dim(self, widget=None, data=None, dim=None):
        if self.inhibit_change_dim:
            return
        self.inhibit_change_dim = True
        if widget:
            for dim in [1,2]:
                if self.xml.get_object('dim '+str(dim)).get_active():
                    self.dim = dim
                    break
        else:
            self.dim = dim
            self.xml.get_object('dim '+str(dim)).set_active(True)

        self.shape = self.recalculate_shape()
        self.startpos = None
        self.inhibit_reconfigure = True        #"change_calculator" would call a useless "reconfigure"
        self.calculators_menu()
        self.inhibit_reconfigure = False
        self.initialize()
        self.inhibit_change_dim = False

    def recalculate_shape(self, steps=None, dim=None):
        if not steps:
            steps = self.STEPS
        if not dim:
            dim = self.dim
        
        shape = [int(steps**(1/float(dim)))]*dim

        # Not ready for 3 dimensions.
        # Also: this cycle will run at most 2 times, so I don't bother about
        # overhead of testing dim also the second:
        while dim > 1 and shape[0] * (shape[1] + 1) <= self.STEPS:
            shape[1] += 1
        
        return tuple(shape)

    def change_mpf(self, spin, *args):
        self.MPF = int(1000/spin.get_value())
        if self.runner:
            GObject.source_remove(self.runner)
            self.runner=GObject.timeout_add(self.MPF, self.update)

    def change_disposition(self, menu_item=None, pos=None):

        if menu_item:
            new_dim = int(menu_item.get_name().partition(' ')[0])
            self.disposition = menu_item.get_name().partition(' ')[2]
            self.startpos = None

        else:
            self.startpos = pos
            new_dim=len(self.startpos.shape)

        if new_dim is not self.dim:
            self.change_dim(dim=new_dim)
        elif menu_item:
            self.points.reconfigure(disp=self.disposition)
        else:
            self.points.reconfigure(pos=pos)

        self.stop()
        self.drawn_time=0

    def change_calculator(self, combobox=None, arg2=None):
        if self.points and not self.inhibit_reconfigure:
            self.points.reconfigure(calc=combobox.get_active_text())
            self.xml.get_object('granularity').set_sensitive(self.points.calculator.discrete)
            self.drawn_time = 0

    def start(self):
        if not self.runner:
            self.runner=GObject.timeout_add(self.MPF, self.update)
            self.labeler=GObject.timeout_add_seconds(2, self.set_labels)
            self.start_button.set_label(_('Stop'))

    def stop(self, *args):
        if self.runner:
            GObject.source_remove(self.runner)
            GObject.source_remove(self.labeler)
            self.runner = 0
            self.start_button.set_label(_('Start'))

    def start_stop(self, *args):
        if self.runner:
            self.stop()
        else:
            self.start()

    def update(self, *args):

        if self.occupied and (self.points.drawer.dumpdir or WAIT_FRAMES):    #If we are dumping, we can wait, user won't notice it.
            return True

        self.occupied = True
        elapsed_ms = self.points.update(self.drawn_time)
        if elapsed_ms:
            self.elapsed_ms=elapsed_ms
        
        self.draw_ms = self.points.drawer.drawing_time

        self.drawn_time=self.drawn_time+self.MPF*(float(self.speed)*min(self.shape)/100)

        self.occupied = False


        return True

    def set_labels(self, *args):
        self.frame_number.set_text(str(self.points.number))
        self.frame_ms.set_text(str(round(self.elapsed_ms, 3)))
        self.draw_ms_label.set_text(str(round(self.draw_ms, 3)))

        return True

    def dispositions_menu(self):
        main_menu = self.xml.get_object('dispositions menu')
        for dim in DIMS:
            if dim == 1:
                submenu_title = _('%d dimension: precooked')
                advanced_title = _('%d dimension: advanced')
            else:
                submenu_title = _('%d dimensions: precooked')
                advanced_title = _('%d dimensions: advanced')
            submenu_header=Gtk.MenuItem(submenu_title % dim)
            submenu=Gtk.Menu()
            for disposition in dispositions.dispositions[dim]:
                disposition_item = Gtk.MenuItem(_(disposition))
                disposition_item.set_name(str(dim)+' '+disposition)
                disposition_item.connect('activate', self.change_disposition)
                submenu.append(disposition_item)
            submenu_header.set_submenu(submenu)
            submenu_header.show()
            submenu.show_all()
            main_menu.append(submenu_header)
            advanced_item = Gtk.MenuItem(advanced_title % dim)
            advanced_item.connect('activate', self.editor_start, dim)
            advanced_item.show()
            main_menu.append(advanced_item)

    def calculators_menu(self):
        self.build_menu('calculator', calculators.calculators)

    def build_menu(self, name, items):
        combo = self.xml.get_object('combo '+name)
        combo_model=Gtk.ListStore(str)
        for item in items[self.dim]:
            combo_model.append([item])
        combo.set_model(combo_model)
        combo.set_active(0)


    def editor_start(self, *args):
        self.stop()

        new_shape = self.recalculate_shape(self.STEPS, args[1])
        if len(new_shape) != len(self.shape):
            self.change_dim(dim=len(new_shape))

        if self.editor:
            self.editor.go(self.points, new_shape)
        else:
            self.editor=AdvancedEditor(self, self.xml, self.points, new_shape)
        

    def editor_save(self, points):
        self.change_disposition(pos=points.pos)

    def editor_esc(self):
        self.editor.window.hide()
        del self.editor

    def show_about(self, *args):
        self.about_window=self.xml.get_object('about')
        self.about_window.run()
        self.about_window.hide()

    def show_help(self, *args):
        if INSTALLED:
            Gtk.show_uri(None, 'help:gvb', Gdk.CURRENT_TIME)
        else:
            import locale
            loc = locale.getdefaultlocale()[0]
            if os.path.exists('%s/%s/docbook.index' % (HELP_DIR, loc)):
                Gtk.show_uri(None, 'ghelp://%s/%s/index.docbook' % (HELP_DIR, loc), Gdk.CURRENT_TIME)
            elif os.path.exists('%s/%s/gvb.xml' % (HELP_DIR, loc.split('_')[0])):
                Gtk.show_uri(None, 'ghelp://%s/%s/index.docbook' % (HELP_DIR, loc.split('_')[0]), Gdk.CURRENT_TIME)
            else:
                Gtk.show_uri(None, 'ghelp://%s/C/index.docbook' % HELP_DIR, Gdk.CURRENT_TIME)

    def change_steps(self, *args):
        self.steps_window = self.xml.get_object('steps')
        self.xml.get_object('steps spin').set_adjustment(Gtk.Adjustment(self.STEPS, 1, 10000, 1, 10))
        response = self.steps_window.run()
        self.steps_window.hide()

        if response == 1:
            self.startpos = None

            new_steps = int(self.xml.get_object('steps spin').get_value())
            if new_steps != self.STEPS:
                self.STEPS = new_steps
                self.shape = self.recalculate_shape()
                self.initialize()
        else:
            self.xml.get_object('steps spin').set_value(self.STEPS)

    def quit(self, *args):
        Gtk.main_quit()

    def save(self, *args):
        if self.filename:
            if self.runner:
                self.stop()
                self.points.dump(self.filename)
                self.start()
            else:
                self.points.dump(self.filename)
        else:
            self.save_as(*args)

    def save_as(self, *args):
        self.stop()
        file_chooser = self.xml.get_object('file chooser')
        self.xml.get_object('file chooser button').set_label('gtk-save')
        
        while True:
            response = file_chooser.run()

            filename = file_chooser.get_filename()
            if not filename or not response == 2:
                file_chooser.hide()
                return

            if os.path.exists(filename):
                response_exists = self.xml.get_object('file exists')
                response_exists.run()
                response_exists.hide()
                if response_exists != 3:
                    # 3 is "Overwrite"
                    continue
            break

        self.filename = filename
        self.points.dump(self.filename)
        file_chooser.hide()

    def load(self, *args):
        self.stop()
        file_chooser = self.xml.get_object('file chooser')
        self.xml.get_object('file chooser button').set_label('gtk-open')

        while True:
            response = file_chooser.run()
            filename = file_chooser.get_filename()
            if not filename or response != 2:
                file_chooser.hide()
                return

            if not os.path.exists(filename):
                    not_exists_dialog = self.xml.get_object('file not exists')
                    not_exists_dialog.run()
                    not_exists_dialog.hide()
                    continue
            file_chooser.hide()
            self.filename = filename
            break

        self.points=points.Points(drawer = drawers.Drawer(self.drawing, self.xml.get_object('combo drawer')),
                                    gr = self.xml.get_object('granularity').get_value(),
                                    from_file = self.filename)

        self.shape = self.points.pos.shape
        # FIXME to load in 2 dims:
        self.STEPS = self.shape[0]
        self.xml.get_object('steps spin').set_value(self.STEPS)
        self.startpos = self.points.pos

        self.initialize()

    def png_dump(self, *args):
        if self.dumping:
            self.points.drawer.dump(None)
            self.dumping = False
            return
        self.stop()
        file_chooser = self.xml.get_object('file chooser')
        self.xml.get_object('file chooser button').set_label('gtk-save')
        while True:
            response = file_chooser.run()
            filename = file_chooser.get_filename()
            
            if not filename or response != 2:
                file_chooser.hide()
                # The user changed her mind - no dump:
                self.xml.get_object('png dump').set_active(False)
                return

            if os.path.exists(filename):
                if not os.path.isdir(filename):
                    file_exists_dialog = self.xml.get_object('file exists')
                    file_exists_response = file_exists_dialog.run()
                    file_exists_dialog.hide()
                    if file_exists_response != 3:
                        # OK, he's sure
                        os.remove(filename)
                        os.mkdir(filename)
                    else:
                        continue
            else:
                os.mkdir(filename)

            file_chooser.hide()

            self.dumping = True
            self.points.drawer.dump(filename)
        

if __name__=='__main__':
    app=MainGbv()
    Gtk.main()