forked from dkobozev/tatlin
/
tatlin.py
486 lines (392 loc) · 16.8 KB
/
tatlin.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
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
482
483
484
485
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Denis Kobozev
#
# 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 2 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 __future__ import division
import sys
import os, os.path
import logging
from libtatlin.actors import Platform
from libtatlin.scene import Scene
from libtatlin.ui import load_icon, BaseApp, MainWindow, StlPanel, GcodePanel, \
OpenDialog, OpenErrorAlert, ProgressDialog, SaveDialog, QuitDialog, AboutDialog
from libtatlin.storage import ModelFile, ModelFileError
from libtatlin.config import Config
def format_float(f):
return "%.2f" % f
def resolve_path(fpath):
if os.path.isabs(fpath):
return fpath
if getattr(sys, 'frozen', False):
# we are running in a PyInstaller bundle
basedir = sys._MEIPASS
else:
# we are running in a normal Python environment
basedir = os.path.dirname(__file__)
return os.path.join(basedir, fpath)
class App(BaseApp):
TATLIN_VERSION = '0.2.5'
TATLIN_LICENSE = """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 2 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
"""
RECENT_FILE_LIMIT = 10
def __init__(self):
super(App, self).__init__()
# ---------------------------------------------------------------------
# WINDOW SETUP
# ---------------------------------------------------------------------
self.window = MainWindow()
self.icon = load_icon(resolve_path('tatlin-logo.png'))
self.window.set_icon(self.icon)
# ---------------------------------------------------------------------
# APP SETUP
# ---------------------------------------------------------------------
self.init_config()
recent_files = self.config.read('ui.recent_files')
if recent_files:
self.recent_files = []
for f in recent_files.split(os.path.pathsep):
if f[-1] in ['0', '1', '2']:
fpath, ftype = f[:-1], OpenDialog.ftypes[int(f[-1])]
else:
fpath, ftype = f, None
if os.path.exists(fpath):
self.recent_files.append((os.path.basename(fpath), fpath, ftype))
self.recent_files = self.recent_files[:self.RECENT_FILE_LIMIT]
else:
self.recent_files = []
self.window.update_recent_files_menu(self.recent_files)
window_w = self.config.read('ui.window_w', int)
window_h = self.config.read('ui.window_h', int)
self.window.set_size((window_w, window_h))
self.init_scene()
def init_config(self):
fname = os.path.expanduser(os.path.join('~', '.tatlin'))
self.config = Config(fname)
def init_scene(self):
self.panel = None
self.scene = None
self.model_file = None
# dict of properties that other components can read from the app
self._app_properties = {
'layers_range_max': lambda: self.scene.get_property('max_layers'),
'layers_value': lambda: self.scene.get_property('max_layers'),
'scaling-factor': self.model_scaling_factor,
'width': self.model_width,
'depth': self.model_depth,
'height': self.model_height,
'rotation-x': self.model_rotation_x,
'rotation-y': self.model_rotation_y,
'rotation-z': self.model_rotation_z,
}
def show_window(self):
self.window.show_all()
# -------------------------------------------------------------------------
# PROPERTIES
# -------------------------------------------------------------------------
def get_property(self, name):
"""
Return a property of the application.
"""
return self._app_properties[name]()
def model_scaling_factor(self):
factor = self.scene.get_property('scaling-factor')
return format_float(factor)
def model_width(self):
width = self.scene.get_property('width')
return format_float(width)
def model_depth(self):
depth = self.scene.get_property('depth')
return format_float(depth)
def model_height(self):
height = self.scene.get_property('height')
return format_float(height)
def model_rotation_x(self):
angle = self.scene.get_property('rotation-x')
return format_float(angle)
def model_rotation_y(self):
angle = self.scene.get_property('rotation-y')
return format_float(angle)
def model_rotation_z(self):
angle = self.scene.get_property('rotation-z')
return format_float(angle)
@property
def current_dir(self):
"""
Return path where a file should be saved to.
"""
if self.model_file is not None:
dur = self.model_file.dirname
elif len(self.recent_files) > 0:
dur = os.path.dirname(self.recent_files[0][1])
else:
dur = os.getcwd()
return dur
def command_line(self):
if len(sys.argv) > 1:
self.open_and_display_file(os.path.abspath(sys.argv[1]))
# -------------------------------------------------------------------------
# EVENT HANDLERS
# -------------------------------------------------------------------------
def on_file_open(self, event=None):
if self.save_changes_dialog():
show_again = True
while show_again:
dialog = OpenDialog(self.window, self.current_dir)
fpath = dialog.get_path()
if fpath:
show_again = not self.open_and_display_file(fpath, dialog.get_type())
else:
show_again = False
def on_file_save(self, event=None):
"""
Save changes to the same file.
"""
self.scene.export_to_file(self.model_file)
self.window.file_modified = False
def on_file_save_as(self, event=None):
"""
Save changes to a new file.
"""
dialog = SaveDialog(self.window, self.current_dir)
fpath = dialog.get_path()
if fpath:
stl_file = ModelFile(fpath)
self.scene.export_to_file(stl_file)
self.model_file = stl_file
self.window.filename = stl_file.basename
self.window.file_modified = False
def on_quit(self, event=None):
"""
On quit, write config settings and show a dialog proposing to save the
changes if the scene has been modified.
"""
try:
self.config.write('ui.recent_files', os.path.pathsep.join([f[1] + str(OpenDialog.ftypes.index(f[2]))
for f in self.recent_files]))
w, h = self.window.get_size()
self.config.write('ui.window_w', w)
self.config.write('ui.window_h', h)
if self.scene:
self.config.write('ui.gcode_2d', int(self.scene.mode_2d))
self.config.commit()
except IOError:
logging.warning('Could not write settings to config file %s' % self.config.fname)
if self.save_changes_dialog():
self.window.quit()
def save_changes_dialog(self):
proceed = True
if self.scene and self.scene.model_modified:
ask_again = True
while ask_again:
dialog = QuitDialog(self.window)
response = dialog.show()
if response == QuitDialog.RESPONSE_SAVE:
self.on_file_save()
ask_again = False
elif response == QuitDialog.RESPONSE_SAVE_AS:
self.on_file_save_as()
ask_again = self.scene.model_modified
elif response == QuitDialog.RESPONSE_CANCEL:
ask_again = False
proceed = False
elif response == QuitDialog.RESPONSE_DISCARD:
ask_again = False
else:
logging.warning('Unknown dialog response: %s' % response)
ask_again = False
proceed = False
return proceed
def on_about(self, event=None):
AboutDialog()
def scaling_factor_changed(self, factor):
try:
self.scene.scale_model(float(factor))
self.scene.invalidate()
# tell all the widgets that care about model size that it has changed
self.panel.model_size_changed()
self.window.file_modified = self.scene.model_modified
except ValueError:
pass # ignore invalid values
def dimension_changed(self, dimension, value):
try:
self.scene.change_model_dimension(dimension, float(value))
self.scene.invalidate()
self.panel.model_size_changed()
self.window.file_modified = self.scene.model_modified
except ValueError:
pass # ignore invalid values
def on_layers_changed(self, layers):
self.scene.change_num_layers(layers)
self.scene.invalidate()
def rotation_changed(self, axis, angle):
try:
self.scene.rotate_model(float(angle), axis)
self.scene.invalidate()
self.window.file_modified = self.scene.model_modified
except ValueError:
pass # ignore invalid values
def on_center_model(self):
"""
Center model on platform.
"""
self.scene.center_model()
self.scene.invalidate()
self.window.file_modified = self.scene.model_modified
def on_arrows_toggled(self, value):
"""
Show/hide arrows on the Gcode model.
"""
self.scene.show_arrows(value)
self.scene.invalidate()
def on_reset_view(self):
"""
Restore the view of the model shown on startup.
"""
self.scene.reset_view()
self.scene.invalidate()
def on_set_mode(self, value):
self.scene.mode_2d = not value
if self.scene.initialized:
self.scene.invalidate()
def on_set_ortho(self, value):
self.scene.mode_ortho = value
self.scene.invalidate()
def on_view_front(self):
self.scene.rotate_view(0, 0)
def on_view_back(self):
self.scene.rotate_view(180, 0)
def on_view_left(self):
self.scene.rotate_view(90, 0)
def on_view_right(self):
self.scene.rotate_view(-90, 0)
def on_view_top(self):
self.scene.rotate_view(0, -90)
def on_view_bottom(self):
self.scene.rotate_view(0, 90)
# -------------------------------------------------------------------------
# FILE OPERATIONS
# -------------------------------------------------------------------------
def update_recent_files(self, fpath, ftype=None):
self.recent_files = [f for f in self.recent_files if f[1] != fpath]
self.recent_files.insert(0, (os.path.basename(fpath), fpath, ftype))
self.recent_files = self.recent_files[:self.RECENT_FILE_LIMIT]
self.window.update_recent_files_menu(self.recent_files)
def open_and_display_file(self, fpath, ftype=None):
self.set_wait_cursor()
progress_dialog_read = None
progress_dialog_load = None
success = True
try:
self.update_recent_files(fpath, ftype)
self.model_file = ModelFile(fpath, ftype)
self.scene = Scene(self.window)
progress_dialog_read = ProgressDialog('Reading file...')
model, model_data = self.model_file.read(progress_dialog_read.step)
progress_dialog_load = ProgressDialog('Loading model...')
model.load_data(model_data, progress_dialog_load.step)
self.scene.clear()
self.scene.add_model(model)
if self.model_file.filetype == 'gcode':
offset_x = self.config.read('machine.platform_offset_x', float)
offset_y = self.config.read('machine.platform_offset_y', float)
offset_z = self.config.read('machine.platform_offset_z', float)
if offset_x is None and offset_y is None and offset_z is None:
self.scene.view_model_center()
logging.info('Platform offsets not set, showing model in the center')
else:
model.offset_x = offset_x if offset_x is not None else 0
model.offset_y = offset_y if offset_y is not None else 0
model.offset_z = offset_z if offset_z is not None else 0
logging.info('Using platform offsets: (%s, %s, %s)' % (
model.offset_x, model.offset_y, model.offset_z))
# platform needs to be added last to be translucent
platform_w = self.config.read('machine.platform_w', float)
platform_d = self.config.read('machine.platform_d', float)
platform = Platform(platform_w, platform_d)
self.scene.add_supporting_actor(platform)
self.panel = self.create_panel()
# update panel to reflect new model properties
self.panel.set_initial_values()
self.panel.connect_handlers()
# always start with the same view on the scene
self.scene.reset_view(True)
if self.model_file.filetype == 'gcode':
self.scene.mode_2d = bool(self.config.read('ui.gcode_2d', int))
else:
self.scene.mode_2d = False
if hasattr(self.panel, 'set_3d_view'):
self.panel.set_3d_view(not self.scene.mode_2d)
self.window.set_file_widgets(self.scene, self.panel)
self.window.filename = self.model_file.basename
self.window.file_modified = False
self.window.menu_enable_file_items(self.model_file.filetype != 'gcode')
if self.model_file.size > 2**30:
size = self.model_file.size / 2**30
units = 'GB'
elif self.model_file.size > 2**20:
size = self.model_file.size / 2**20
units = 'MB'
elif self.model_file.size > 2**10:
size = self.model_file.size / 2**10
units = 'KB'
else:
size = self.model_file.size
units = 'B'
vertex_plural = 'vertex' if int(str(model.vertex_count)[-1]) == 1 else 'vertices'
self.window.update_status(' %s (%.1f%s, %d %s)' % (
self.model_file.basename, size, units, model.vertex_count, vertex_plural))
except IOError, e:
self.set_normal_cursor()
error_dialog = OpenErrorAlert(fpath, e.strerror)
error_dialog.show()
success = False
except ModelFileError, e:
self.set_normal_cursor()
error_dialog = OpenErrorAlert(fpath, e.message)
error_dialog.show()
success = False
finally:
if progress_dialog_read:
progress_dialog_read.destroy()
if progress_dialog_load:
progress_dialog_load.destroy()
self.set_normal_cursor()
return success
def create_panel(self):
if self.model_file.filetype == 'gcode':
Panel = GcodePanel
elif self.model_file.filetype == 'stl':
Panel = StlPanel
return Panel(self.window)
def panel_matches_file(self):
matches = (self.model_file.filetype in self.panel.supported_types)
return matches
if __name__ == '__main__':
# configure logging
logging.basicConfig(format='--- [%(levelname)s] %(message)s', level=logging.DEBUG)
app = App()
app.show_window()
app.command_line()
app.run()