File: wxVRML2X3D.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (297 lines) | stat: -rw-r--r-- 10,273 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
# -*- coding: utf-8 -*-

import os
import sys

from DisplayCAL.meta import name as appname
from DisplayCAL.util_os import launch_file, make_win32_compatible_long_path, waccess
from DisplayCAL import config
from DisplayCAL import localization as lang
from DisplayCAL import x3dom

gui = "wx" in sys.modules

if gui:
    from DisplayCAL.worker import Worker, show_result_dialog
    from DisplayCAL.wxaddons import wx
    from DisplayCAL.wxfixes import GenBitmapButton as BitmapButton
    from DisplayCAL.wxwindows import BaseApp, BaseFrame, FileDrop

    class VRML2X3DFrame(BaseFrame):
        def __init__(self, html, embed, view, force, cache):
            BaseFrame.__init__(
                self,
                None,
                wx.ID_ANY,
                lang.getstr("vrml_to_x3d_converter"),
                style=wx.DEFAULT_FRAME_STYLE & ~(wx.MAXIMIZE_BOX | wx.RESIZE_BORDER),
                name="vrml2x3dframe",
            )
            self.SetIcons(
                config.get_icon_bundle(
                    [256, 48, 32, 16], "%s-VRML-to-X3D-converter" % appname
                )
            )
            self.Bind(wx.EVT_CLOSE, self.OnClose)
            self.cache = cache
            self.embed = embed
            self.force = force
            self.html = html
            self.worker = Worker(self)
            sizer = wx.BoxSizer(wx.HORIZONTAL)
            self.SetSizer(sizer)
            panel = wx.Panel(self)
            sizer.Add(panel)
            panelsizer = wx.BoxSizer(wx.HORIZONTAL)
            panel.SetSizer(panelsizer)
            self.btn = BitmapButton(
                panel,
                wx.ID_ANY,
                config.geticon(256, "3d-primitives"),
                style=wx.NO_BORDER,
            )
            self.btn.SetToolTipString(lang.getstr("file.select"))
            self.btn.Bind(
                wx.EVT_BUTTON,
                lambda event: vrmlfile2x3dfile(
                    None,
                    html=html,
                    embed=embed,
                    view=view,
                    force=force,
                    cache=cache,
                    worker=self.worker,
                ),
            )
            self.droptarget = FileDrop(self)
            vrml_drop_handler = lambda vrmlpath: vrmlfile2x3dfile(
                vrmlpath,
                html=html,
                embed=embed,
                view=view,
                force=force,
                cache=cache,
                worker=self.worker,
            )
            self.droptarget.drophandlers = {
                ".vrml": vrml_drop_handler,
                ".vrml.gz": vrml_drop_handler,
                ".wrl": vrml_drop_handler,
                ".wrl.gz": vrml_drop_handler,
                ".wrz": vrml_drop_handler,
            }
            self.btn.SetDropTarget(self.droptarget)
            panelsizer.Add(self.btn, flag=wx.ALL, border=12)
            self.Fit()
            self.SetMinSize(self.GetSize())
            self.SetMaxSize(self.GetSize())

        def OnClose(self, event):
            # Hide first (looks nicer)
            self.Hide()
            # Need to use CallAfter to prevent hang under Windows if minimized
            wx.CallAfter(self.Destroy)

        def get_commands(self):
            return self.get_common_commands() + [
                "VRML-to-X3D-converter [filename...]",
                "load <filename...>",
            ]

        def process_data(self, data):
            if data[0] in ("VRML-to-X3D-converter", "load"):
                if self.IsIconized():
                    self.Restore()
                self.Raise()
                if len(data) > 1:
                    self.droptarget.OnDropFiles(0, 0, data[1:])
                return "ok"
            return "invalid"


def main():
    if "--help" in sys.argv[1:] or (not sys.argv[1:] and not gui):
        print("Convert VRML file to X3D")
        print("Author: Florian Hoech, licensed under the GPL version 3")
        print("Usage: %s [OPTION]... FILE..." % os.path.basename(sys.argv[0]))
        print("The output is written to FILENAME.x3d(.html)")
        print("")
        print(
            "  --embed      Embed viewer components in HTML instead of referencing them"
        )
        print("  --force      Force fresh download of viewer components")
        print(
            "  --no-cache   Don't use viewer components cache (only uses existing cache if"
        )
        print("               embedding components, can be overridden with --force)")
        if gui:
            print("  --no-gui     Don't use GUI (console mode)")
        print("  --no-html    Don't generate HTML file")
        print("  --view       View the generated file (if no GUI)")
        if not gui:
            print("  --batch      Don't pause after processing")
        print("  FILE         Filename of VRML file to convert")
        if gui:
            return
    if gui:
        config.initcfg("VRML-to-X3D-converter")
        lang.init()
        lang.update_defaults()
    cache = "--no-cache" not in sys.argv[1:]
    embed = "--embed" in sys.argv
    force = "--force" in sys.argv
    html = "--no-html" not in sys.argv[1:]
    if not gui:
        result = None
        view = "--view" in sys.argv[1:]
        for arg in sys.argv[1:]:
            if not arg.startswith("--"):
                result = vrmlfile2x3dfile(
                    str(arg),
                    html=html,
                    embed=embed,
                    view=view,
                    force=force,
                    cache=cache,
                    gui=gui,
                )
        if result is None:
            print("No filename given.")
        if (
            sys.stdout
            and hasattr(sys.stdout, "isatty")
            and sys.stdout.isatty()
            and "--batch" not in sys.argv[1:]
        ):
            input("Press RETURN to exit")
        sys.exit(int(not result))
    else:
        view = "--no-view" not in sys.argv[1:]
        app = BaseApp(0)
        app.TopWindow = VRML2X3DFrame(html, embed, view, force, cache)
        if sys.platform == "darwin":
            app.TopWindow.init_menubar()
        wx.CallLater(1, _main, app)
        app.MainLoop()


def _main(app):
    app.TopWindow.listen()
    app.process_argv()
    app.TopWindow.Show()


def vrmlfile2x3dfile(
    vrmlpath=None,
    x3dpath=None,
    html=True,
    embed=False,
    view=False,
    force=False,
    cache=True,
    worker=None,
    gui=True,
):
    """Convert VRML to HTML. Output is written to <vrmlfilename>.x3d.html
    unless you set x3dpath to desired output path, or False to be prompted
    for an output path."""
    while not vrmlpath or not os.path.isfile(vrmlpath):
        if not gui:
            if not vrmlpath or vrmlpath.startswith("--"):
                print("No filename given.")
            else:
                print("%r is not a file." % vrmlpath)
            return False
        if not wx.GetApp():
            app = BaseApp(0)
        defaultDir, defaultFile = config.get_verified_path("last_vrml_path")
        dlg = wx.FileDialog(
            None,
            lang.getstr("file.select"),
            defaultDir=defaultDir,
            defaultFile=defaultFile,
            wildcard=lang.getstr("filetype.vrml")
            + "|*.vrml;*.vrml.gz;*.wrl.gz;*.wrl;*.wrz",
            style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
        )
        dlg.Center(wx.BOTH)
        result = dlg.ShowModal()
        vrmlpath = dlg.GetPath()
        dlg.Destroy()
        if result != wx.ID_OK:
            return
        config.setcfg("last_vrml_path", vrmlpath)
        config.writecfg(module="VRML-to-X3D-converter", options=("last_vrml_path",))
    filename, ext = os.path.splitext(vrmlpath)
    if x3dpath is None:
        x3dpath = f"{filename}.x3d"
    if x3dpath:
        dirname = os.path.dirname(x3dpath)
    while not x3dpath or not waccess(dirname, os.W_OK):
        if not gui:
            if not x3dpath:
                print("No HTML output filename given.")
            else:
                print(f"{repr(dirname)} is not writable.")
            return False
        if not wx.GetApp():
            app = BaseApp(0)
        if x3dpath:
            defaultDir, defaultFile = os.path.split(x3dpath)
        else:
            defaultFile = os.path.basename(filename) + ".x3d"
        dlg = wx.FileDialog(
            None,
            lang.getstr("error.access_denied.write", dirname),
            defaultDir=defaultDir,
            defaultFile=defaultFile,
            wildcard=lang.getstr("filetype.x3d") + "|*.x3d",
            style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
        )
        dlg.Center(wx.BOTH)
        result = dlg.ShowModal()
        dlg.Destroy()
        if result != wx.ID_OK:
            return
        x3dpath = dlg.GetPath()
        dirname = os.path.dirname(x3dpath)
    vrmlpath, x3dpath = [str(path) for path in (vrmlpath, x3dpath)]
    if sys.platform == "win32":
        vrmlpath = make_win32_compatible_long_path(vrmlpath)
        x3dpath = make_win32_compatible_long_path(x3dpath)
    if html:
        finalpath = f"{x3dpath}.html"
        if sys.platform == "win32":
            finalpath = make_win32_compatible_long_path(finalpath)
            x3dpath = finalpath[:-5]
    else:
        finalpath = x3dpath
    if worker:
        worker.clear_cmd_output()
        worker.start(
            lambda result: (
                show_result_dialog(result, wx.GetApp().GetTopWindow())
                if isinstance(result, Exception)
                else result and view and launch_file(finalpath)
            ),
            x3dom.vrmlfile2x3dfile,
            wargs=(vrmlpath, x3dpath, html, embed, force, cache, worker),
            progress_title=lang.getstr("vrml_to_x3d_converter"),
            progress_start=1,
            resume=worker.progress_wnd and worker.progress_wnd.IsShownOnScreen(),
            fancy=False,
        )
    else:
        result = x3dom.vrmlfile2x3dfile(
            vrmlpath, x3dpath, html, embed, force, cache, None
        )
        if not isinstance(result, Exception) and result:
            if view:
                launch_file(finalpath)
        else:
            return False
    return True


if __name__ == "__main__":
    main()