]> git.mxchange.org Git - flightgear.git/blob - src/GUI/gui_funcs.cxx
Fix issue #398: Menubar - Help > Help opens strange path when including space character
[flightgear.git] / src / GUI / gui_funcs.cxx
1 /**************************************************************************
2  * gui_funcs.cxx
3  *
4  * Based on gui.cxx and renamed on 2002/08/13 by Erik Hofman.
5  *
6  * Written 1998 by Durk Talsma, started Juni, 1998.  For the flight gear
7  * project.
8  *
9  * Additional mouse supported added by David Megginson, 1999.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 of the
14  * License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24  *
25  * $Id$
26  **************************************************************************/
27
28
29 #ifdef HAVE_CONFIG_H
30 #  include <config.h>
31 #endif
32
33 #include <simgear/compiler.h>
34
35 #include <fstream>
36 #include <string>
37 #include <cstring>
38 #include <sstream>
39
40 #include <stdlib.h>
41
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/misc/sg_path.hxx>
44 #include <simgear/screen/screen-dump.hxx>
45 #include <simgear/structure/event_mgr.hxx>
46 #include <simgear/props/props_io.hxx>
47
48 #include <Cockpit/panel.hxx>
49 #include <Main/globals.hxx>
50 #include <Main/fg_props.hxx>
51 #include <Main/fg_os.hxx>
52 #include <Main/renderer.hxx>
53 #include <Main/viewmgr.hxx>
54 #include <Main/WindowSystemAdapter.hxx>
55 #include <Main/CameraGroup.hxx>
56 #include <GUI/new_gui.hxx>
57
58
59 #ifdef _WIN32
60 #  include <shellapi.h>
61 #endif
62
63 #include "gui.h"
64
65 using std::string;
66
67
68 #if defined( TR_HIRES_SNAP)
69 #include <simgear/screen/tr.h>
70 extern void fgUpdateHUD( GLfloat x_start, GLfloat y_start,
71                          GLfloat x_end, GLfloat y_end );
72 #endif
73
74
75 const __fg_gui_fn_t __fg_gui_fn[] = {
76 #ifdef TR_HIRES_SNAP
77         {"dumpHiResSnapShot", fgHiResDumpWrapper},
78 #endif
79         {"dumpSnapShot", fgDumpSnapShotWrapper},
80         // Help
81         {"helpCb", helpCb},
82
83         // Structure termination
84         {"", NULL}
85 };
86
87
88 /* ================ General Purpose Functions ================ */
89
90 // General Purpose Message Box. Makes sure no more than 5 different
91 // messages are displayed at the same time, and none of them are
92 // duplicates. (5 is a *lot*, but this will hardly ever be reached
93 // and we don't want to miss any, either.)
94 void mkDialog (const char *txt)
95 {
96     NewGUI *gui = (NewGUI *)globals->get_subsystem("gui");
97     if (!gui)
98         return;
99     SGPropertyNode *master = gui->getDialogProperties("message");
100     if (!master)
101         return;
102
103     const int maxdialogs = 5;
104     string name;
105     SGPropertyNode *msg = fgGetNode("/sim/gui/dialogs", true);
106     int i;
107     for (i = 0; i < maxdialogs; i++) {
108         std::ostringstream s;
109         s << "message-" << i;
110         name = s.str();
111
112         if (!msg->getNode(name.c_str(), false))
113             break;
114
115         if (!strcmp(txt, msg->getNode(name.c_str())->getStringValue("message"))) {
116             SG_LOG(SG_GENERAL, SG_WARN, "mkDialog(): duplicate of message " << txt);
117             return;
118         }
119     }
120     if (i == maxdialogs)
121         return;
122     msg = msg->getNode(name.c_str(), true);
123     msg->setStringValue("message", txt);
124     msg = msg->getNode("dialog", true);
125     copyProperties(master, msg);
126     msg->setStringValue("name", name.c_str());
127     gui->newDialog(msg);
128     gui->showDialog(name.c_str());
129 }
130
131 // Message Box to report an error.
132 void guiErrorMessage (const char *txt)
133 {
134     SG_LOG(SG_GENERAL, SG_ALERT, txt);
135     mkDialog(txt);
136 }
137
138 // Message Box to report a throwable (usually an exception).
139 void guiErrorMessage (const char *txt, const sg_throwable &throwable)
140 {
141     string msg = txt;
142     msg += '\n';
143     msg += throwable.getFormattedMessage();
144     if (!std::strlen(throwable.getOrigin()) != 0) {
145         msg += "\n (reported by ";
146         msg += throwable.getOrigin();
147         msg += ')';
148     }
149     SG_LOG(SG_GENERAL, SG_ALERT, msg);
150     mkDialog(msg.c_str());
151 }
152
153
154
155 /* -----------------------------------------------------------------------
156 the Gui callback functions 
157 ____________________________________________________________________*/
158
159
160 // Hier Neu :-) This is my newly added code
161 // Added by David Findlay <nedz@bigpond.com>
162 // on Sunday 3rd of December
163
164
165 void helpCb ()
166 {
167     string command;
168         
169     SGPath path( globals->get_fg_root() );
170     path.append( "Docs/index.html" );
171         
172 #ifndef _WIN32
173
174     command = globals->get_browser();
175     string::size_type pos;
176     if ((pos = command.find("%u", 0)) != string::npos)
177         command.replace(pos, 2, path.str());
178     else
179         command += " " + path.str();
180
181     command += " &";
182     system( command.c_str() );
183
184 #else // _WIN32
185
186     // Look for favorite browser
187     char win32_name[1024];
188 # ifdef __CYGWIN__
189     cygwin32_conv_to_full_win32_path(path.c_str(),win32_name);
190 # else
191     strncpy(win32_name,path.c_str(), 1024);
192 # endif
193     ShellExecute ( NULL, "open", win32_name, NULL, NULL,
194                    SW_SHOWNORMAL ) ;
195
196 #endif
197         
198     mkDialog ("Help started in your web browser window.");
199 }
200
201 #if defined( TR_HIRES_SNAP)
202 void fgHiResDump()
203 {
204     FILE *f;
205     string message;
206     bool menu_status = fgGetBool("/sim/menubar/visibility");
207     char *filename = new char [24];
208     static int count = 1;
209
210     static const SGPropertyNode *master_freeze
211         = fgGetNode("/sim/freeze/master");
212
213     bool freeze = master_freeze->getBoolValue();
214     if ( !freeze ) {
215         fgSetBool("/sim/freeze/master", true);
216     }
217
218     fgSetBool("/sim/menubar/visibility", false);
219     int mouse = fgGetMouseCursor();
220     fgSetMouseCursor(MOUSE_CURSOR_NONE);
221
222     FGRenderer *renderer = globals->get_renderer();
223 //     renderer->init();
224     renderer->resize( fgGetInt("/sim/startup/xsize"),
225                       fgGetInt("/sim/startup/ysize") );
226
227     // we need two render frames here to clear the menu and cursor
228     // ... not sure why but doing an extra fgRenderFrame() shouldn't
229     // hurt anything
230     //renderer->update( true );
231     //renderer->update( true );
232
233     // This ImageSize stuff is a temporary hack
234     // should probably use 128x128 tile size and
235     // support any image size
236
237     // This should be a requester to get multiplier from user
238     int multiplier = fgGetInt("/sim/startup/hires-multiplier", 3);
239     int width = fgGetInt("/sim/startup/xsize");
240     int height = fgGetInt("/sim/startup/ysize");
241         
242     /* allocate buffer large enough to store one tile */
243     GLubyte *tile = (GLubyte *)malloc(width * height * 3 * sizeof(GLubyte));
244     if (!tile) {
245         delete [] filename;
246         printf("Malloc of tile buffer failed!\n");
247         return;
248     }
249
250     int imageWidth  = multiplier*width;
251     int imageHeight = multiplier*height;
252
253     /* allocate buffer to hold a row of tiles */
254     GLubyte *buffer
255         = (GLubyte *)malloc(imageWidth * height * 3 * sizeof(GLubyte));
256     if (!buffer) {
257         delete [] filename;
258         free(tile);
259         printf("Malloc of tile row buffer failed!\n");
260         return;
261     }
262     TRcontext *tr = trNew();
263     trTileSize(tr, width, height, 0);
264     trTileBuffer(tr, GL_RGB, GL_UNSIGNED_BYTE, tile);
265     trImageSize(tr, imageWidth, imageHeight);
266     trRowOrder(tr, TR_TOP_TO_BOTTOM);
267     // OSGFIXME
268 //     sgFrustum *frustum = ssgGetFrustum();
269 //     trFrustum(tr,
270 //               frustum->getLeft(), frustum->getRight(),
271 //               frustum->getBot(),  frustum->getTop(), 
272 //               frustum->getNear(), frustum->getFar());
273         
274     /* Prepare ppm output file */
275     while (count < 1000) {
276         snprintf(filename, 24, "fgfs-screen-%03d.ppm", count++);
277         if ( (f = fopen(filename, "r")) == NULL )
278             break;
279         fclose(f);
280     }
281     f = fopen(filename, "wb");
282     if (!f) {
283         printf("Couldn't open image file: %s\n", filename);
284         delete [] filename;
285         free(buffer);
286         free(tile);
287         return;
288     }
289     fprintf(f,"P6\n");
290     fprintf(f,"# ppm-file created by %s\n", "trdemo2");
291     fprintf(f,"%i %i\n", imageWidth, imageHeight);
292     fprintf(f,"255\n");
293
294     /* just to be safe... */
295     glPixelStorei(GL_PACK_ALIGNMENT, 1);
296
297     // OSGFIXME
298 #if 0
299     /* Because the HUD and Panel change the ViewPort we will
300      * need to handle some lowlevel stuff ourselves */
301     int ncols = trGet(tr, TR_COLUMNS);
302     int nrows = trGet(tr, TR_ROWS);
303
304     bool do_hud = fgGetBool("/sim/hud/visibility");
305     GLfloat hud_col_step = 640.0 / ncols;
306     GLfloat hud_row_step = 480.0 / nrows;
307         
308     bool do_panel = fgPanelVisible();
309     GLfloat panel_col_step = globals->get_current_panel()->getWidth() / ncols;
310     GLfloat panel_row_step = globals->get_current_panel()->getHeight() / nrows;
311 #endif
312     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
313     glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
314     glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
315     glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
316     glHint(GL_FOG_HINT, GL_NICEST);
317         
318     /* Draw tiles */
319     int more = 1;
320     while (more) {
321         trBeginTile(tr);
322         int curColumn = trGet(tr, TR_CURRENT_COLUMN);
323         // int curRow =  trGet(tr, TR_CURRENT_ROW);
324
325         renderer->update( false );
326         // OSGFIXME
327 //         if ( do_hud )
328 //             fgUpdateHUD( curColumn*hud_col_step,      curRow*hud_row_step,
329 //                          (curColumn+1)*hud_col_step, (curRow+1)*hud_row_step );
330         // OSGFIXME
331 //         if (do_panel)
332 //             globals->get_current_panel()->update(
333 //                                    curColumn*panel_col_step, panel_col_step,
334 //                                    curRow*panel_row_step,    panel_row_step );
335         more = trEndTile(tr);
336
337         /* save tile into tile row buffer*/
338         int curTileWidth = trGet(tr, TR_CURRENT_TILE_WIDTH);
339         int bytesPerImageRow = imageWidth * 3*sizeof(GLubyte);
340         int bytesPerTileRow = (width) * 3*sizeof(GLubyte);
341         int xOffset = curColumn * bytesPerTileRow;
342         int bytesPerCurrentTileRow = (curTileWidth) * 3*sizeof(GLubyte);
343         int i;
344         for (i=0;i<height;i++) {
345             memcpy(buffer + i*bytesPerImageRow + xOffset, /* Dest */
346                    tile + i*bytesPerTileRow,              /* Src */
347                    bytesPerCurrentTileRow);               /* Byte count*/
348         }
349
350         if (curColumn == trGet(tr, TR_COLUMNS)-1) {
351             /* write this buffered row of tiles to the file */
352             int curTileHeight = trGet(tr, TR_CURRENT_TILE_HEIGHT);
353             int bytesPerImageRow = imageWidth * 3*sizeof(GLubyte);
354             int i;
355             for (i=0;i<curTileHeight;i++) {
356                 /* Remember, OpenGL images are bottom to top.  Have to reverse. */
357                 GLubyte *rowPtr = buffer + (curTileHeight-1-i) * bytesPerImageRow;
358                 fwrite(rowPtr, 1, imageWidth*3, f);
359             }
360         }
361
362     }
363
364     renderer->resize( width, height );
365
366     trDelete(tr);
367
368     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
369     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
370     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
371     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
372     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
373          (!fgGetBool("/sim/rendering/shading"))) {
374         // if fastest fog requested, or if flat shading force fastest
375         glHint ( GL_FOG_HINT, GL_FASTEST );
376     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
377         glHint ( GL_FOG_HINT, GL_DONT_CARE );
378     }
379
380     fclose(f);
381
382     message = "Snapshot saved to \"";
383     message += filename;
384     message += "\".";
385     mkDialog (message.c_str());
386
387     free(tile);
388     free(buffer);
389
390     delete [] filename;
391
392     fgSetMouseCursor(mouse);
393     fgSetBool("/sim/menubar/visibility", menu_status);
394
395     if ( !freeze ) {
396         fgSetBool("/sim/freeze/master", false);
397     }
398 }
399 #endif // #if defined( TR_HIRES_SNAP)
400
401 void fgDumpSnapShotWrapper () {
402     fgDumpSnapShot();
403 }
404
405
406 void fgHiResDumpWrapper () {
407     fgHiResDump();
408 }
409
410 namespace
411 {
412     using namespace flightgear;
413
414     class GUISnapShotOperation : 
415         public GraphicsContextOperation
416     {
417     public:
418
419         // start new snap shot
420         static bool start()
421         {
422             // allow only one snapshot at a time
423             if (_snapShotOp.valid())
424                 return false;
425             _snapShotOp = new GUISnapShotOperation();
426             /* register with graphics context so actual snap shot is done
427              * in the graphics context (thread) */
428             osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
429             WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
430             osg::GraphicsContext* gc = 0;
431             if (guiCamera)
432                 gc = guiCamera->getGraphicsContext();
433             if (gc) {
434                 gc->add(_snapShotOp.get());
435             } else {
436                 wsa->windows[0]->gc->add(_snapShotOp.get());
437             }
438             return true;
439         }
440
441     private:
442         // constructor to be executed in main loop's thread
443         GUISnapShotOperation() :
444             flightgear::GraphicsContextOperation(std::string("GUI snap shot")),
445             _master_freeze(fgGetNode("/sim/freeze/master", true)),
446             _freeze(_master_freeze->getBoolValue()),
447             _result(false),
448             _mouse(fgGetMouseCursor())
449         {
450             if (!_freeze)
451                 _master_freeze->setBoolValue(true);
452
453             fgSetMouseCursor(MOUSE_CURSOR_NONE);
454
455             string dir = fgGetString("/sim/paths/screenshot-dir");
456             if (dir.empty())
457                 dir = fgGetString("/sim/fg-current");
458
459             _path.set(dir + '/');
460             if (_path.create_dir( 0755 )) {
461                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot create screenshot directory '"
462                         << dir << "'. Trying home directory.");
463                 dir = fgGetString("/sim/fg-home");
464             }
465
466             char filename[24];
467             static int count = 1;
468             while (count < 1000) {
469                 snprintf(filename, 24, "fgfs-screen-%03d.png", count++);
470
471                 SGPath p(dir);
472                 p.append(filename);
473                 if (!p.exists()) {
474                     _path.set(p.str());
475                     break;
476                 }
477             }
478
479             _xsize = fgGetInt("/sim/startup/xsize");
480             _ysize = fgGetInt("/sim/startup/ysize");
481
482             FGRenderer *renderer = globals->get_renderer();
483             renderer->resize(_xsize, _ysize);
484             globals->get_event_mgr()->addTask("SnapShotTimer",
485                     this, &GUISnapShotOperation::timerExpired,
486                     0.1, false);
487         }
488
489         // to be executed in graphics context (maybe separate thread)
490         void run(osg::GraphicsContext* gc)
491         {
492             _result = sg_glDumpWindow(_path.c_str(),
493                                      _xsize,
494                                      _ysize);
495         }
496
497         // timer method, to be executed in main loop's thread
498         virtual void timerExpired()
499         {
500             if (isFinished())
501             {
502                 globals->get_event_mgr()->removeTask("SnapShotTimer");
503
504                 fgSetString("/sim/paths/screenshot-last", _path.c_str());
505                 fgSetBool("/sim/signals/screenshot", _result);
506
507                 fgSetMouseCursor(_mouse);
508
509                 if ( !_freeze )
510                     _master_freeze->setBoolValue(false);
511
512                 _snapShotOp = 0;
513             }
514         }
515     
516         static osg::ref_ptr<GUISnapShotOperation> _snapShotOp;
517         SGPropertyNode_ptr _master_freeze;
518         bool _freeze;
519         bool _result;
520         int _mouse;
521         int _xsize, _ysize;
522         SGPath _path;
523     };
524
525 }
526
527 osg::ref_ptr<GUISnapShotOperation> GUISnapShotOperation::_snapShotOp;
528
529 // do a screen snap shot
530 bool fgDumpSnapShot ()
531 {
532 #if 1
533     // start snap shot operation, while needs to be executed in
534     // graphics context
535     return GUISnapShotOperation::start();
536 #else
537     // obsolete code => remove when new code is stable
538     static SGConstPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master");
539
540     bool freeze = master_freeze->getBoolValue();
541     if ( !freeze ) {
542         fgSetBool("/sim/freeze/master", true);
543     }
544
545     int mouse = fgGetMouseCursor();
546     fgSetMouseCursor(MOUSE_CURSOR_NONE);
547
548     fgSetBool("/sim/signals/screenshot", true);
549
550     FGRenderer *renderer = globals->get_renderer();
551     renderer->resize( fgGetInt("/sim/startup/xsize"),
552                       fgGetInt("/sim/startup/ysize") );
553
554     // we need two render frames here to clear the menu and cursor
555     // ... not sure why but doing an extra fgRenderFrame() shouldn't
556     // hurt anything
557     renderer->update( true );
558     renderer->update( true );
559
560     string dir = fgGetString("/sim/paths/screenshot-dir");
561     if (dir.empty())
562         dir = fgGetString("/sim/fg-current");
563
564     SGPath path(dir + '/');
565     if (path.create_dir( 0755 )) {
566         SG_LOG(SG_GENERAL, SG_ALERT, "Cannot create screenshot directory '"
567                 << dir << "'. Trying home directory.");
568         dir = fgGetString("/sim/fg-home");
569     }
570
571     char filename[24];
572     static int count = 1;
573     while (count < 1000) {
574         snprintf(filename, 24, "fgfs-screen-%03d.png", count++);
575
576         SGPath p(dir);
577         p.append(filename);
578         if (!p.exists()) {
579             path.set(p.str());
580             break;
581         }
582     }
583
584     bool result = sg_glDumpWindow(path.c_str(),
585                                  fgGetInt("/sim/startup/xsize"),
586                                  fgGetInt("/sim/startup/ysize"));
587
588     fgSetString("/sim/paths/screenshot-last", path.c_str());
589     fgSetBool("/sim/signals/screenshot", false);
590
591     fgSetMouseCursor(mouse);
592
593     if ( !freeze ) {
594         fgSetBool("/sim/freeze/master", false);
595     }
596     return result;
597 #endif
598 }
599
600 // do an entire scenegraph dump
601 void fgDumpSceneGraph()
602 {
603     char *filename = new char [24];
604     string message;
605     static int count = 1;
606
607     static const SGPropertyNode *master_freeze
608         = fgGetNode("/sim/freeze/master");
609
610     bool freeze = master_freeze->getBoolValue();
611     if ( !freeze ) {
612         fgSetBool("/sim/freeze/master", true);
613     }
614
615     while (count < 1000) {
616         FILE *fp;
617         snprintf(filename, 24, "fgfs-graph-%03d.osg", count++);
618         if ( (fp = fopen(filename, "r")) == NULL )
619             break;
620         fclose(fp);
621     }
622
623     if ( fgDumpSceneGraphToFile(filename)) {
624         message = "Entire scene graph saved to \"";
625         message += filename;
626         message += "\".";
627     } else {
628         message = "Failed to save to \"";
629         message += filename;
630         message += "\".";
631     }
632
633     mkDialog (message.c_str());
634
635     delete [] filename;
636
637     if ( !freeze ) {
638         fgSetBool("/sim/freeze/master", false);
639     }
640 }
641
642     
643 // do an terrain branch dump
644 void fgDumpTerrainBranch()
645 {
646     char *filename = new char [24];
647     string message;
648     static int count = 1;
649
650     static const SGPropertyNode *master_freeze
651         = fgGetNode("/sim/freeze/master");
652
653     bool freeze = master_freeze->getBoolValue();
654     if ( !freeze ) {
655         fgSetBool("/sim/freeze/master", true);
656     }
657
658     while (count < 1000) {
659         FILE *fp;
660         snprintf(filename, 24, "fgfs-graph-%03d.osg", count++);
661         if ( (fp = fopen(filename, "r")) == NULL )
662             break;
663         fclose(fp);
664     }
665
666     if ( fgDumpTerrainBranchToFile(filename)) {
667         message = "Terrain graph saved to \"";
668         message += filename;
669         message += "\".";
670     } else {
671         message = "Failed to save to \"";
672         message += filename;
673         message += "\".";
674     }
675
676     mkDialog (message.c_str());
677
678     delete [] filename;
679
680     if ( !freeze ) {
681         fgSetBool("/sim/freeze/master", false);
682     }
683 }
684
685 void fgPrintVisibleSceneInfoCommand()
686 {
687     static const SGPropertyNode *master_freeze
688         = fgGetNode("/sim/freeze/master");
689
690     bool freeze = master_freeze->getBoolValue();
691     if ( !freeze ) {
692         fgSetBool("/sim/freeze/master", true);
693     }
694
695     flightgear::printVisibleSceneInfo(globals->get_renderer());
696
697     if ( !freeze ) {
698         fgSetBool("/sim/freeze/master", false);
699     }
700 }
701
702     
703